diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-10-17 08:59:57 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-10-17 08:59:57 -0500 |
| commit | 352def9012790ab97252715697291ba4c0ebec01 (patch) | |
| tree | 0b8d6e2340ce40818ddbbea2de0db4019b5e45a3 /src | |
| parent | 593308d4e786cd569e3a683f5b02b8f13aa39b23 (diff) | |
| parent | 9379a1fa3af07bab44b81752fe808cb9ca94be7a (diff) | |
| download | slskd-352def9012790ab97252715697291ba4c0ebec01.tar.gz | |
Merge pull request #697 from slskd/agent
Add the ability to 'network' multiple copies of slskd together (enable remote shares)
Diffstat (limited to 'src')
30 files changed, 2095 insertions, 445 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index fa7ed516..bdb55ca4 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> applicationHub, IHubContext<LogsHub> 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,8 +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>() == 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) + { + _ = NetworkClient.StartAsync(cancellationToken); + } + await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); } } @@ -430,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); @@ -709,7 +726,7 @@ namespace slskd var place = Transfers.Uploads.Queue.EstimatePosition(username, filename); return Task.FromResult((int?)place); } - catch (FileNotFoundException) + catch (NotFoundException) { return Task.FromResult<int?>(null); } @@ -1036,14 +1053,34 @@ namespace slskd } } - private async Task CacheBrowseResponse() + private async Task<BrowseResponse> 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) diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 8fb1fd25..561162d4 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -325,27 +325,6 @@ namespace slskd } /// <summary> - /// Converts the byte array into a base 62 encoded string. - /// </summary> - /// <param name="bytes">The bytes to convert.</param> - /// <returns>The converted bytes as a base 62 string.</returns> - 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(); - } - - /// <summary> /// Determines whether the given object is a <see cref="Dictionary{TKey, TValue}"/>. /// </summary> /// <param name="obj">The object to check.</param> diff --git a/src/slskd/Common/Cryptography/Aes.cs b/src/slskd/Common/Cryptography/Aes.cs new file mode 100644 index 00000000..9828d7f8 --- /dev/null +++ b/src/slskd/Common/Cryptography/Aes.cs @@ -0,0 +1,112 @@ +// <copyright file="Aes.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Cryptography +{ + using System; + using System.IO; + using System.Linq; + using System.Security.Cryptography; + + /// <summary> + /// AES utility methods. + /// </summary> + 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; + + /// <summary> + /// Decrypts the specified <paramref name="encryptedBytes"/> with the specified <paramref name="key"/>. + /// </summary> + /// <param name="encryptedBytes">The encrypted data to decrypt.</param> + /// <param name="key">The encryption key.</param> + /// <returns>The decrypted data.</returns> + public static byte[] Decrypt(byte[] encryptedBytes, byte[] key) + { + using var aes = System.Security.Cryptography.Aes.Create(); + + aes.KeySize = KeySizeInBits; + aes.BlockSize = BlockSizeInBits; + + var (k, iv) = DecodeKey(key); + + 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(); + + cryptoStream.CopyTo(outputStream); + + return outputStream.ToArray(); + } + + /// <summary> + /// Encrypts the specified <paramref name="plainBytes"/> with the specified <paramref name="key"/>. + /// </summary> + /// <param name="plainBytes">The plain data to encrypt.</param> + /// <param name="key">The encryption key.</param> + /// <returns>The encrypted data.</returns> + public static byte[] Encrypt(byte[] plainBytes, byte[] key) + { + using var aes = System.Security.Cryptography.Aes.Create(); + + aes.KeySize = KeySizeInBits; + aes.BlockSize = BlockSizeInBits; + + var (k, iv) = DecodeKey(key); + + using var encryptor = aes.CreateEncryptor(k, iv); + using var outputStream = new MemoryStream(); + using var cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write); + + cryptoStream.Write(plainBytes, 0, plainBytes.Length); + cryptoStream.Flush(); + cryptoStream.Close(); + + return outputStream.ToArray(); + } + + /// <summary> + /// Generates a random key using the default key and block sizes. + /// </summary> + /// <returns>The generated key.</returns> + public static byte[] GenerateRandomKey() + { + 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(byte[] bytes) + { + var mem = new Memory<byte>(bytes); + var key = mem.Slice(0, KeySizeInBytes); + var iv = mem.Slice(KeySizeInBytes, BlockSizeInBytes); + + return (key.ToArray(), iv.ToArray()); + } + } +}
\ No newline at end of file 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 + */ +// <auto-generated /> -- 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"; + + /// <summary> + /// Encode a 2-byte number with Base62 + /// </summary> + /// <param name="original">String</param> + /// <param name="inverted">Use inverted character set</param> + /// <returns>Base62 string</returns> + 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); + } + + /// <summary> + /// Encode a 4-byte number with Base62 + /// </summary> + /// <param name="original">String</param> + /// <param name="inverted">Use inverted character set</param> + /// <returns>Base62 string</returns> + 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); + } + + /// <summary> + /// Encode a 8-byte number with Base62 + /// </summary> + /// <param name="original">String</param> + /// <param name="inverted">Use inverted character set</param> + /// <returns>Base62 string</returns> + 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); + } + + /// <summary> + /// Encode a string with Base62 + /// </summary> + /// <param name="original">String</param> + /// <param name="inverted">Use inverted character set</param> + /// <returns>Base62 string</returns> + public static string ToBase62(this string original, bool inverted = false) + { + return Encoding.UTF8.GetBytes(original).ToBase62(inverted); + } + + /// <summary> + /// Encode a byte array with Base62 + /// </summary> + /// <param name="original">Byte array</param> + /// <param name="inverted">Use inverted character set</param> + /// <returns>Base62 string</returns> + 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(); + } + + /// <summary> + /// Decode a base62-encoded string + /// </summary> + /// <param name="base62">Base62 string</param> + /// <param name="inverted">Use inverted character set</param> + /// <returns>Byte array</returns> + public static T FromBase62<T>(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."); + } + } + + /// <summary> + /// Decode a base62-encoded string + /// </summary> + /// <param name="base62">Base62 string</param> + /// <param name="inverted">Use inverted character set</param> + /// <returns>Byte array</returns> + 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<int>(); + var leadingZeroCount = Math.Min(source.TakeWhile(x => x == 0).Count(), source.Length - 1); + int count; + while ((count = source.Length) > 0) + { + var quotient = new List<int>(); + 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 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 file="NetworkException.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents an error related to the slskd network feature. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class NetworkException : SlskdException + { + /// <summary> + /// Initializes a new instance of the <see cref="NetworkException"/> class. + /// </summary> + public NetworkException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="NetworkException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public NetworkException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="NetworkException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public NetworkException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="NetworkException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected NetworkException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file 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; /// <summary> @@ -34,14 +35,15 @@ namespace slskd /// <param name="onFailure">An action to execute on failure.</param> /// <param name="maxAttempts">The maximum number of retry attempts.</param> /// <param name="maxDelayInMilliseconds">The maximum delay in milliseconds.</param> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The execution context.</returns> - public static async Task Do(Func<Task> task, Func<int, Exception, bool> isRetryable = null, Action<int, Exception> onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + public static async Task Do(Func<Task> task, Func<int, Exception, bool> isRetryable = null, Action<int, Exception> onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue, CancellationToken cancellationToken = default) { await Do<object>(async () => { await task(); return Task.FromResult<object>(null); - }, isRetryable, onFailure, maxAttempts, maxDelayInMilliseconds); + }, isRetryable, onFailure, maxAttempts, maxDelayInMilliseconds, cancellationToken); } /// <summary> @@ -52,9 +54,10 @@ namespace slskd /// <param name="onFailure">An action to execute on failure.</param> /// <param name="maxAttempts">The maximum number of retry attempts.</param> /// <param name="maxDelayInMilliseconds">The maximum delay in miliseconds.</param> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <typeparam name="T">The Type of the logic return value.</typeparam> /// <returns>The execution context.</returns> - public static async Task<T> Do<T>(Func<Task<T>> task, Func<int, Exception, bool> isRetryable = null, Action<int, Exception> onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + public static async Task<T> Do<T>(Func<Task<T>> task, Func<int, Exception, bool> isRetryable = null, Action<int, Exception> 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(); diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 484a514b..b75f9356 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; @@ -132,12 +133,22 @@ namespace slskd /// </summary> [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; /// <summary> + /// Gets a value indicating whether to generate a random agent secret. + /// </summary> + [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; + + /// <summary> /// Gets a value indicating whether the application should run in debug mode. /// </summary> [Argument('d', "debug")] @@ -181,7 +192,7 @@ namespace slskd /// <summary> /// Gets the path where application data is saved. /// </summary> - [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")] @@ -201,6 +212,12 @@ namespace slskd public string ConfigurationFile { get; init; } = Program.DefaultConfigurationFile; /// <summary> + /// Gets network options. + /// </summary> + [Validate] + public NetworkOptions Network { get; init; } = new NetworkOptions(); + + /// <summary> /// Gets directory options. /// </summary> [Validate] @@ -345,6 +362,97 @@ namespace slskd [Description("log SQL queries generated by Entity Framework")] [RequiresRestart] public bool LogSQL { get; init; } = false; + + /// <summary> + /// Gets a value indicating whether to run in both controller and agent network modes. + /// </summary> + [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; + } + + /// <summary> + /// Network options. + /// </summary> + public class NetworkOptions : IValidatableObject + { + /// <summary> + /// Gets the application operation mode. + /// </summary> + [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(); + + /// <summary> + /// Gets the controller configuration. + /// </summary> + public NetworkControllerConfigurationOptions Controller { get; init; } = new NetworkControllerConfigurationOptions(); + + /// <summary> + /// Gets the agent configuration. + /// </summary> + public Dictionary<string, NetworkAgentConfigurationOptions> Agents { get; init; } = new(); + + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + // todo: can't run in agent mode if instancename is default + + //var controllerResults = new List<ValidationResult>(); + //var agentResults = new List<ValidationResult>(); + + //if (OperationMode.ToEnum<NetworkOperationMode>() == NetworkOperationMode.Agent && !Validator.TryValidateObject(Controller, validationContext, controllerResults)) + //{ + // results.AddRange(controllerResults); + //} + //else if (!Validator.TryValidateObject(Agents, validationContext, results)) + //{ + // results.AddRange(agentResults); + //} + + return results; + } + + /// <summary> + /// Network controller configuration options. + /// </summary> + public class NetworkControllerConfigurationOptions + { + /// <summary> + /// Gets the controller address. + /// </summary> + [Argument(default, "controller-address")] + [EnvironmentVariable("CONTROLLER_ADDRESS")] + public string Address { get; init; } + + /// <summary> + /// Gets the controller secret. + /// </summary> + [Argument(default, "controller-secret")] + [EnvironmentVariable("CONTROLLER_SECRET")] + [StringLength(48, MinimumLength = 48)] + [Secret] + public string Secret { get; init; } + } + + /// <summary> + /// Network agent configuration options. + /// </summary> + public class NetworkAgentConfigurationOptions + { + /// <summary> + /// Gets the agent secret. + /// </summary> + [StringLength(48, MinimumLength = 48)] + [Secret] + public string Secret { get; init; } + } } /// <summary> @@ -1246,7 +1354,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(); /// <summary> /// Gets the TTL for JWTs, in milliseconds. diff --git a/src/slskd/Shares/Types/HostType.cs b/src/slskd/Core/Types/NetworkOperationMode.cs index 6a892dff..4b190275 100644 --- a/src/slskd/Shares/Types/HostType.cs +++ b/src/slskd/Core/Types/NetworkOperationMode.cs @@ -1,4 +1,4 @@ -// <copyright file="HostType.cs" company="slskd Team"> +// <copyright file="NetworkOperationMode.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -15,21 +15,21 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -namespace slskd.Shares +namespace slskd { /// <summary> - /// The type of host. + /// The network operation mode. /// </summary> - public enum HostType + public enum NetworkOperationMode { /// <summary> - /// Local. + /// Controller operation mode. /// </summary> - Local = 0, + Controller = 0, /// <summary> - /// Remote; shares are hosted by an Agent. + /// Agent operation mode. /// </summary> - Remote = 1, + Agent = 1, } } 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/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs new file mode 100644 index 00000000..21373749 --- /dev/null +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -0,0 +1,146 @@ +// <copyright file="NetworkController.cs" company="slskd Team"> +// 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/. +// </copyright> + +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; + + /// <summary> + /// Network. + /// </summary> + [Route("api/v{version:apiVersion}/[controller]")] + [ApiVersion("0")] + [ApiController] + public class NetworkController : ControllerBase + { + 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<NetworkController>(); + + [HttpPost("files/{id}")] + [Authorize] + public async Task<IActionResult> 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.PendingFileUploads.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.Stream.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(); + } + } + + [HttpPost("shares/{id}")] + [Authorize] + public async Task<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(); + } + + IEnumerable<Share> shares; + IFormFile database; + + try + { + shares = Request.Form["shares"].ToString().FromJson<IEnumerable<Share>>(); + database = Request.Form.Files[0]; + } + catch (Exception ex) + { + 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"); + + Log.Debug("Uploading share from {Agent} to {Filename}", agent, temp); + + using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); + using var inputStream = database.OpenReadStream(); + + await inputStream.CopyToAsync(outputStream); + + Log.Debug("Upload of share from {Agent} to {Filename} complete", agent, temp); + + var repository = ShareRepositoryFactory.CreateFromFile(temp); + + if (!repository.TryValidate(out var problems)) + { + return BadRequest("Invalid database: " + string.Join(", ", problems)); + } + + var destinationRepository = ShareRepositoryFactory.CreateFromHost(agent); + + destinationRepository.RestoreFrom(repository); + + Shares.AddOrUpdateHost(new Host(agent, shares)); + + return Ok(); + } + } +} diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs new file mode 100644 index 00000000..f79fecf2 --- /dev/null +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -0,0 +1,125 @@ +// <copyright file="NetworkHub.cs" company="slskd Team"> +// 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/. +// </copyright> + +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 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"; + } + + /// <summary> + /// Extension methods for the network SignalR hub. + /// </summary> + public static class NetworkHubExtensions + { + public static Task RequestFileAsync(this IHubContext<NetworkHub> 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); + } + + public static Task RequestFileInfoAsync(this IHubContext<NetworkHub> hub, string agent, string filename, Guid id) + { + return hub.Clients.All.SendAsync(NetworkHubMethods.RequestFileInfo, filename, id); + } + } + + /// <summary> + /// The network SignalR hub. + /// </summary> + [Authorize] + public class NetworkHub : Hub + { + public NetworkHub( + INetworkService networkService) + { + Network = networkService; + } + + private INetworkService Network { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<NetworkService>(); + + 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(Context.ConnectionId, agent); + return true; + } + + Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); + 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 + 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.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)); + } + } + } +}
\ No newline at end of file diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs new file mode 100644 index 00000000..baaa1250 --- /dev/null +++ b/src/slskd/Network/NetworkClient.cs @@ -0,0 +1,340 @@ +// <copyright file="NetworkClient.cs" company="slskd Team"> +// 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/. +// </copyright> + +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 Microsoft.Data.Sqlite; + using Serilog; + using slskd.Cryptography; + using slskd.Shares; + + public interface INetworkClient + { + Task StartAsync(CancellationToken cancellationToken = default); + Task StopAsync(CancellationToken cancellationToken = default); + } + + public class NetworkClient : INetworkClient + { + public NetworkClient( + IShareService shareService, + IOptionsMonitor<Options> optionsMonitor, + IHttpClientFactory httpClientFactory) + { + Shares = shareService; + + HttpClientFactory = httpClientFactory; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); + } + + private IShareService Shares { get; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private string LastOptionsHash { get; set; } + private IOptionsMonitor<Options> 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; } + private ILogger Log { get; } = Serilog.Log.ForContext<NetworkClient>(); + private TaskCompletionSource LoggedIn { get; set; } + + public async Task StartAsync(CancellationToken cancellationToken = default) + { + if (OptionsMonitor.CurrentValue.Network.OperationMode.ToEnum<NetworkOperationMode>() != 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); + LoggedIn = new TaskCompletionSource(); + 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. Awaiting authentication..."); + + await LoggedIn.Task; + + Log.Information("Authenticated. Uploading shares..."); + + try + { + await UploadSharesAsync(); + } + catch (Exception ex) + { + Log.Error(ex, ex.Message); + Log.Error("Disconnecting from the network controller"); + await StopAsync(); + throw; + } + + Log.Information("Shares uploaded. Ready to upload files."); + } + + public async Task StopAsync(CancellationToken cancellationToken = default) + { + StartRequested = false; + + if (HubConnection != null) + { + await HubConnection.StopAsync(cancellationToken); + + Log.Information("Network controller connection disconnected"); + } + } + + 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); + await Shares.DumpAsync(temp); + Log.Debug("Share backup successful"); + + Log.Debug("Requesting share upload token..."); + var token = await HubConnection.InvokeAsync<Guid>(nameof(NetworkHub.GetShareUploadToken)); + Log.Debug("Share upload token {Token}", token); + + var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); + + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/shares/{token}"); + using var content = new MultipartFormDataContent + { + { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" }, + { new StreamContent(stream), "database", "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(string filename, Guid id) + { + Log.Information("Network controller requested file {Filename} with ID {Id}", filename, id); + + try + { + var (_, localFilename) = await Shares.ResolveFileAsync(filename); + + var localFileInfo = new FileInfo(localFilename); + + 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/network/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); + } + else + { + 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. + await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyUploadFailed), id); + } + } + + 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"); + + 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.Debug("Logging in..."); + var success = await HubConnection.InvokeAsync<bool>(nameof(NetworkHub.Login), agent, response); + + if (!success) + { + await HubConnection.StopAsync(); + Log.Error("Network controller authentication failed. Check configuration."); + } + + Log.Debug("Login succeeded."); + LoggedIn?.TrySetResult(); + } + 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>() != NetworkOperationMode.Agent && !options.Flags.DualNetworkMode) + { + return; + } + + SyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(options.Network.Controller.ToJson()); + + if (optionsHash == LastOptionsHash) + { + return; + } + + 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 + // 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<string, Guid>(NetworkHubMethods.RequestFile, HandleFileRequest); + HubConnection.On<string, Guid>(NetworkHubMethods.RequestFileInfo, HandleFileInfoRequest); + HubConnection.On<string>(NetworkHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); + + LastOptionsHash = optionsHash; + + Log.Debug("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 new file mode 100644 index 00000000..d857cac5 --- /dev/null +++ b/src/slskd/Network/NetworkService.cs @@ -0,0 +1,370 @@ +// <copyright file="NetworkService.cs" company="slskd Team"> +// 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/. +// </copyright> + +using Microsoft.Extensions.Options; + +namespace slskd.Network +{ + using System; + 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; + using Serilog; + using slskd.Cryptography; + + public interface INetworkService + { + /// <summary> + /// Gets the collection of pending Agent file uploads. + /// </summary> + ReadOnlyDictionary<Guid, (TaskCompletionSource<Stream> Stream, TaskCompletionSource Completion)> PendingFileUploads { get; } + + /// <summary> + /// Gets the collection of pending Agent file inquiries. + /// </summary> + ReadOnlyDictionary<Guid, TaskCompletionSource<(bool Exists, long Length)>> PendingFileInquiries { get; } + + /// <summary> + /// Gets the collection of registered Agents. + /// </summary> + ReadOnlyDictionary<string, string> RegisteredAgents { get; } + + /// <summary> + /// Retrieves information about the specified <paramref name="filename"/> from the specified <paramref name="agent"/>. + /// </summary> + /// <param name="agent">The agent from which to retrieve the file information.</param> + /// <param name="filename">The file for which to retrieve information.</param> + /// <param name="timeout">An optional timeout value.</param> + /// <returns>A value indicating whether the file exists, and the length in bytes.</returns> + Task<(bool Exists, long Length)> GetFileInfo(string agent, string filename, int timeout = 3000); + + /// <summary> + /// Retrieves an upload of the specified <paramref name="filename"/> from the specified <paramref name="agent"/>. + /// </summary> + /// <param name="agent">The agent from which to retrieve the file.</param> + /// <param name="filename">The file to retrieve.</param> + /// <param name="timeout">An optional timeout value.</param> + /// <returns>The operation context, including a stream containing the requested file, and an upload TaskCompletionSource.</returns> + Task<(Stream Stream, TaskCompletionSource Completion)> GetFileUpload(string agent, string filename, int timeout = 3000); + + /// <summary> + /// Retrieves a new share upload token for the specified <paramref name="agent"/>. + /// </summary> + /// <remarks> + /// The token is cached internally, and is only valid while it remains in the cache. + /// </remarks> + /// <param name="agent">The name of the agent.</param> + /// <returns>The generated token.</returns> + Guid GetShareUploadToken(string agent); + + /// <summary> + /// Attempts to retrieve the specified share upload <paramref name="token"/>. + /// </summary> + /// <param name="token">The token.</param> + /// <param name="agent">The name of the agent attempting to use the token.</param> + /// <returns>A value indicating whether the specified token exists.</returns> + bool TryGetShareUploadToken(Guid token, out string agent); + + /// <summary> + /// Registers the specified <paramref name="agent"/> name with the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the connection.</param> + /// <param name="agent">The name of the agent.</param> + void RegisterAgent(string connectionId, string agent); + + /// <summary> + /// Attempts to retrieve the registration for the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the agent connection.</param> + /// <param name="agent">The agent, if registered.</param> + /// <returns>A value indicating whether the registration exists.</returns> + bool TryGetAgentRegistration(string connectionId, out string agent); + + /// <summary> + /// Attempts to remove the registration for the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the connection.</param> + /// <param name="agent">The agent, if removed.</param> + /// <returns>A value indicating whether a registration was removed.</returns> + bool TryRemoveAgentRegistration(string connectionId, out string agent); + + /// <summary> + /// Generates a random authentication challenge token for the specified <paramref name="connectionId"/>. + /// </summary> + /// <remarks> + /// The token is cached internally, and is only valid while it remains in the cache. + /// </remarks> + /// <param name="connectionId">The ID of the agent connection.</param> + /// <returns>The generated token.</returns> + string GenerateAuthenticationChallengeToken(string connectionId); + + /// <summary> + /// Validates an authentication challenge response. + /// </summary> + /// <param name="connectionId">The ID of the agent connection.</param> + /// <param name="agent">The agent name.</param> + /// <param name="challengeResponse">The challenge response provided by the agent.</param> + /// <returns>A value indicating whether the response is valid.</returns> + bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse); + } + + public class NetworkService : INetworkService + { + public NetworkService( + IOptionsMonitor<Options> optionsMonitor, + IHubContext<NetworkHub> networkHub) + { + NetworkHub = networkHub; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + + Configure(OptionsMonitor.CurrentValue); + } + + /// <summary> + /// Gets the collection of pending Agent uploads. + /// </summary> + public ReadOnlyDictionary<Guid, (TaskCompletionSource<Stream> Stream, TaskCompletionSource Completion)> PendingFileUploads => new(PendingFileUploadDictionary); + + /// <summary> + /// Gets the collection of pending Agent file inquiries. + /// </summary> + public ReadOnlyDictionary<Guid, TaskCompletionSource<(bool Exists, long Length)>> PendingFileInquiries => new(PendingFileInquiryDictionary); + + /// <summary> + /// Gets the collection of registered Agents. + /// </summary> + public ReadOnlyDictionary<string, string> RegisteredAgents => new(RegisteredAgentDictionary); + + private ConcurrentDictionary<Guid, (TaskCompletionSource<Stream> Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); + private ConcurrentDictionary<Guid, TaskCompletionSource<(bool Exists, long Length)>> PendingFileInquiryDictionary { get; } = new(); + private ConcurrentDictionary<string, string> RegisteredAgentDictionary { get; } = new(); + private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); + private IOptionsMonitor<Options> OptionsMonitor { get; } + private IHubContext<NetworkHub> NetworkHub { get; set; } + private ILogger Log { get; } = Serilog.Log.ForContext<NetworkService>(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + + /// <summary> + /// Retrieves information about the specified <paramref name="filename"/> from the specified <paramref name="agent"/>. + /// </summary> + /// <param name="agent">The agent from which to retrieve the file information.</param> + /// <param name="filename">The file for which to retrieve information.</param> + /// <param name="timeout">An optional timeout value.</param> + /// <returns>A value indicating whether the file exists, and the length in bytes.</returns> + 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 _); + } + } + + /// <summary> + /// Retrieves an upload of the specified <paramref name="filename"/> from the specified <paramref name="agent"/>. + /// </summary> + /// <param name="agent">The agent from which to retrieve the file.</param> + /// <param name="filename">The file to retrieve.</param> + /// <param name="timeout">An optional timeout value.</param> + /// <returns>The operation context, including a stream containing the requested file, and an upload TaskCompletionSource.</returns> + 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<Stream>(); + + // 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 _); + } + } + + /// <summary> + /// Retrieves a new share upload token for the specified <paramref name="agent"/>. + /// </summary> + /// <remarks> + /// The token is cached internally, and is only valid while it remains in the cache. + /// </remarks> + /// <param name="agent">The name of the agent.</param> + /// <returns>The generated token.</returns> + 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; + } + + /// <summary> + /// Attempts to retrieve the specified share upload <paramref name="token"/>. + /// </summary> + /// <param name="token">The token.</param> + /// <param name="agent">The name of the agent attempting to use the token.</param> + /// <returns>A value indicating whether the specified token exists.</returns> + public bool TryGetShareUploadToken(Guid token, out string agent) + { + agent = null; + + if (MemoryCache.TryGetValue(GetShareTokenCacheKey(token), out agent)) + { + return true; + } + + return false; + } + + /// <summary> + /// Registers the specified <paramref name="agent"/> name with the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the connection.</param> + /// <param name="agent">The name of the agent.</param> + public void RegisterAgent(string connectionId, string agent) + => RegisteredAgentDictionary.TryAdd(connectionId, agent); + + /// <summary> + /// Attempts to retrieve the registration for the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the agent connection.</param> + /// <param name="agent">The agent, if registered.</param> + /// <returns>A value indicating whether the registration exists.</returns> + public bool TryGetAgentRegistration(string connectionId, out string agent) + => RegisteredAgentDictionary.TryGetValue(connectionId, out agent); + + /// <summary> + /// Attempts to remove the registration for the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the connection.</param> + /// <param name="agent">The name of the agent, if a registration was removed.</param> + /// <returns>A value indicating whether a registration was removed.</returns> + public bool TryRemoveAgentRegistration(string connectionId, out string agent) + => RegisteredAgentDictionary.TryRemove(connectionId, out agent); + + /// <summary> + /// Generates a random authentication challenge token for the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the agent connection.</param> + /// <returns>The generated token.</returns> + 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(GetAuthTokenCacheKey(connectionId), token, TimeSpan.FromMinutes(1)); + Log.Debug("Cached auth token {Token} for ID {Id}", token, connectionId); + return token; + } + + /// <summary> + /// Validates an authentication challenge response. + /// </summary> + /// <param name="connectionId">The ID of the agent connection.</param> + /// <param name="agent">The agent name.</param> + /// <param name="challengeResponse">The challenge response provided by the agent.</param> + /// <returns>A value indicating whether the response is valid.</returns> + public bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse) + { + if (!MemoryCache.TryGetValue(GetAuthTokenCacheKey(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; + } + + 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(); + } + } + } +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e744ac54..b9d43992 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -58,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; @@ -206,6 +207,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; } @@ -261,6 +265,7 @@ namespace slskd using (var mutex = new Mutex(reqInitialOwnership, AppName)) { var hasHandle = false; + try { try @@ -270,7 +275,7 @@ namespace slskd Console.WriteLine("Another instance of this program is running"); Environment.Exit(0); } - } + } catch (AbandonedMutexException) { hasHandle = true; @@ -287,13 +292,19 @@ 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; + } + + if (GenerateAgentSecret) + { + Log.Information($"Agent Secret: {Aes.GenerateRandomKey().ToBase62()}"); return; } @@ -517,10 +528,7 @@ namespace slskd services.AddSingleton<IRoomTracker, RoomTracker>(_ => new RoomTracker(messageLimit: 250)); services.AddSingleton<IShareService, ShareService>(); - 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<IShareRepositoryFactory, SqliteShareRepositoryFactory>(); services.AddSingleton<ISearchService, SearchService>(); services.AddSingleton<IUserService, UserService>(); @@ -530,6 +538,9 @@ namespace slskd services.AddSingleton<IDownloadService, DownloadService>(); services.AddSingleton<IUploadService, UploadService>(); + services.AddSingleton<INetworkService, NetworkService>(); + services.AddSingleton<INetworkClient, NetworkClient>(); + services.AddSingleton<IFTPClientFactory, FTPClientFactory>(); services.AddSingleton<IFTPService, FTPService>(); @@ -773,6 +784,7 @@ namespace slskd endpoints.MapHub<ApplicationHub>("/hub/application"); endpoints.MapHub<LogsHub>("/hub/logs"); endpoints.MapHub<SearchHub>("/hub/search"); + endpoints.MapHub<NetworkHub>("/hub/agents"); endpoints.MapControllers(); endpoints.MapHealthChecks("/health"); @@ -993,7 +1005,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); 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 file="IReadOnlyShareRepository.cs" company="slskd Team"> -// 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/. -// </copyright> - -namespace slskd.Shares -{ - /// <summary> - /// Read-only persistent storage of shared files and metadata. - /// </summary> - 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 file="IReadWriteShareRepository.cs" company="slskd Team"> -// 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/. -// </copyright> - -namespace slskd.Shares -{ - using System; - using Soulseek; - - /// <summary> - /// Writeable persistent storage of shared files and metadata. - /// </summary> - public interface IReadWriteShareRepository : IShareRepository - { - - /// <summary> - /// Creates a new database. - /// </summary> - /// <remarks> - /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case - /// tables are explicitly dropped prior to creation. - /// </remarks> - /// <param name="discardExisting">An optional value that determines whether the existing database should be discarded.</param> - void Create(bool discardExisting = false); - - /// <summary> - /// Inserts a directory. - /// </summary> - /// <param name="name">The fully qualified local name of the directory.</param> - /// <param name="timestamp">The timestamp to assign to the record.</param> - void InsertDirectory(string name, long timestamp); - - /// <summary> - /// Inserts a file. - /// </summary> - /// <param name="maskedFilename">The fully qualified remote path of the file.</param> - /// <param name="originalFilename">The fully qualified local path of the file.</param> - /// <param name="touchedAt">The timestamp at which the file was last modified, according to the host OS.</param> - /// <param name="file">The Soulseek.File instance representing the file.</param> - /// <param name="timestamp">The timestamp to assign to the record.</param> - void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file, long timestamp); - - /// <summary> - /// Inserts a scan record at the specified <paramref name="timestamp"/>. - /// </summary> - /// <param name="timestamp">The timestamp associated with the scan.</param> - /// <param name="options">The options snapshot at the start of the scan.</param> - void InsertScan(long timestamp, Options.SharesOptions options); - - /// <summary> - /// Backs the current database up to the database at the specified <paramref name="connectionString"/>. - /// </summary> - /// <param name="connectionString">The connection string of the destination database.</param> - void BackupTo(string connectionString); - - /// <summary> - /// Restores the current database from the database at the specified <paramref name="connectionString"/>. - /// </summary> - /// <param name="connectionString">The connection string of the source database.</param> - void RestoreFrom(string connectionString); - - /// <summary> - /// Deletes directory records with a timestamp prior to the specified <paramref name="olderThanTimestamp"/>. - /// </summary> - /// <param name="olderThanTimestamp">The timestamp before which to delete directories.</param> - /// <returns>The number of records deleted.</returns> - long PruneDirectories(long olderThanTimestamp); - - /// <summary> - /// Deletes file records with a timestamp prior to the specified <paramref name="olderThanTimestamp"/>. - /// </summary> - /// <param name="olderThanTimestamp">The timestamp before which to delete files.</param> - /// <returns>The number of records deleted.</returns> - long PruneFiles(long olderThanTimestamp); - - /// <summary> - /// Updates the scan started at the specified <paramref name="timestamp"/> to set the <paramref name="end"/>. - /// </summary> - /// <param name="timestamp">The timestamp associated with the scan.</param> - /// <param name="end">The timestamp at the conclusion of the scan.</param> - 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; @@ -31,6 +32,12 @@ namespace slskd.Shares string ConnectionString { get; } /// <summary> + /// Backs the current database up to the database at the specified <paramref name="repository"/>. + /// </summary> + /// <param name="repository">The destination repository.</param> + void BackupTo(IShareRepository repository); + + /// <summary> /// Counts the number of directories in the database. /// </summary> /// <param name="parentDirectory">The optional directory prefix used for counting subdirectories.</param> @@ -45,6 +52,22 @@ namespace slskd.Shares int CountFiles(string parentDirectory = null); /// <summary> + /// Creates a new database. + /// </summary> + /// <remarks> + /// Creates tables using 'IF NOT EXISTS', so this is idempotent unless 'discardExisting` is specified, in which case + /// tables are explicitly dropped prior to creation. + /// </remarks> + /// <param name="discardExisting">An optional value that determines whether the existing database should be discarded.</param> + void Create(bool discardExisting = false); + + /// <summary> + /// Dumps the contents of the database to a file. + /// </summary> + /// <param name="filename">The destination file.</param> + void DumpTo(string filename); + + /// <summary> /// Finds the filename of the file matching the specified <paramref name="maskedFilename"/>. /// </summary> /// <param name="maskedFilename">The fully qualified remote path of the file.</param> @@ -52,6 +75,30 @@ namespace slskd.Shares string FindFilename(string maskedFilename); /// <summary> + /// Inserts a directory. + /// </summary> + /// <param name="name">The fully qualified local name of the directory.</param> + /// <param name="timestamp">The timestamp to assign to the record.</param> + void InsertDirectory(string name, long timestamp); + + /// <summary> + /// Inserts a file. + /// </summary> + /// <param name="maskedFilename">The fully qualified remote path of the file.</param> + /// <param name="originalFilename">The fully qualified local path of the file.</param> + /// <param name="touchedAt">The timestamp at which the file was last modified, according to the host OS.</param> + /// <param name="file">The Soulseek.File instance representing the file.</param> + /// <param name="timestamp">The timestamp to assign to the record.</param> + void InsertFile(string maskedFilename, string originalFilename, DateTime touchedAt, File file, long timestamp); + + /// <summary> + /// Inserts a scan record at the specified <paramref name="timestamp"/>. + /// </summary> + /// <param name="timestamp">The timestamp associated with the scan.</param> + /// <param name="options">The options snapshot at the start of the scan.</param> + void InsertScan(long timestamp, Options.SharesOptions options); + + /// <summary> /// Lists all directories. /// </summary> /// <param name="parentDirectory">The optional directory prefix used for listing subdirectories.</param> @@ -67,6 +114,26 @@ namespace slskd.Shares IEnumerable<File> ListFiles(string parentDirectory = null, bool includeFullPath = false); /// <summary> + /// Deletes directory records with a timestamp prior to the specified <paramref name="olderThanTimestamp"/>. + /// </summary> + /// <param name="olderThanTimestamp">The timestamp before which to delete directories.</param> + /// <returns>The number of records deleted.</returns> + long PruneDirectories(long olderThanTimestamp); + + /// <summary> + /// Deletes file records with a timestamp prior to the specified <paramref name="olderThanTimestamp"/>. + /// </summary> + /// <param name="olderThanTimestamp">The timestamp before which to delete files.</param> + /// <returns>The number of records deleted.</returns> + long PruneFiles(long olderThanTimestamp); + + /// <summary> + /// Restores the current database from the database at the specified <paramref name="repository"/>. + /// </summary> + /// <param name="repository">The destination repository.</param> + void RestoreFrom(IShareRepository repository); + + /// <summary> /// Searches the database for files matching the specified <paramref name="query"/>. /// </summary> /// <param name="query">The search query.</param> @@ -74,11 +141,23 @@ namespace slskd.Shares IEnumerable<File> Search(SearchQuery query); /// <summary> - /// Attempts to validate the database at the specified <paramref name="connectionString"/>, or the - /// default <see cref="ConnectionString"/>. + /// Attempts to validate the backing database. + /// </summary> + /// <returns>A value indicating whether the database is valid.</returns> + bool TryValidate(); + + /// <summary> + /// Attempts to validate the backing database. /// </summary> - /// <param name="connectionString">The connection string of the database to validate.</param> + /// <param name="problems">The list of problems, if the database is invalid.</param> /// <returns>A value indicating whether the database is valid.</returns> - bool TryValidate(string connectionString = null); + bool TryValidate(out IEnumerable<string> problems); + + /// <summary> + /// Updates the scan started at the specified <paramref name="timestamp"/> to set the <paramref name="end"/>. + /// </summary> + /// <param name="timestamp">The timestamp associated with the scan.</param> + /// <param name="end">The timestamp at the conclusion of the scan.</param> + 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 file="IShareRepositoryFactory.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Shares +{ + /// <summary> + /// Persistent storage of a shared file cache. + /// </summary> + public interface IShareRepositoryFactory + { + /// <summary> + /// Create a repository for the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the agent.</param> + /// <returns>The created repository.</returns> + IShareRepository CreateFromHost(string name); + + /// <summary> + /// Create a repository backup for the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the agent.</param> + /// <returns>The created repository.</returns> + IShareRepository CreateFromHostBackup(string name); + + /// <summary> + /// Create a repository for the specified <paramref name="filename"/>. + /// </summary> + /// <param name="filename">The fully qualified path of the filename.</param> + /// <returns>The created repository.</returns> + IShareRepository CreateFromFile(string filename); + } +} diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 9d0ba487..34f1bde8 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/. // </copyright> -using System.IO; - namespace slskd.Shares { using System.Collections.Generic; @@ -34,6 +32,11 @@ namespace slskd.Shares IReadOnlyList<Host> Hosts { get; } /// <summary> + /// Gets the local share host. + /// </summary> + Host LocalHost { get; } + + /// <summary> /// Gets the state monitor for the service. /// </summary> IStateMonitor<ShareState> StateMonitor { get; } @@ -51,6 +54,21 @@ namespace slskd.Shares Task<IEnumerable<Directory>> BrowseAsync(Share share = null); /// <summary> + /// Dumps the local share cache to a file. + /// </summary> + /// <param name="filename">The destination file.</param> + /// <returns>The operation context.</returns> + Task DumpAsync(string filename); + + /// <summary> + /// Returns the share host with the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the host.</param> + /// <param name="host">The host, if found.</param> + /// <returns>A value indicating whether the host was found.</returns> + bool TryGetHost(string name, out Host host); + + /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. /// </summary> /// <param name="directory">The directory for which the contents are to be listed.</param> @@ -58,15 +76,27 @@ namespace slskd.Shares Task<Directory> ListDirectoryAsync(string directory); /// <summary> + /// Removes the share host with the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the host.</param> + /// <returns>A value indicating whether the host was removed.</returns> + bool TryRemoveHost(string name); + + /// <summary> /// Resolves the local filename of the specified <paramref name="remoteFilename"/>, if the mask is associated with a /// configured share. /// </summary> /// <param name="remoteFilename">The fully qualified filename to resolve.</param> - /// <returns>The resolved local filename.</returns> + /// <returns>The resolved host and filename.</returns> /// <exception cref="NotFoundException"> /// Thrown when the specified remote filename can not be associated with a configured share. /// </exception> - Task<FileInfo> ResolveFileAsync(string remoteFilename); + Task<(string Host, string Filename)> ResolveFileAsync(string remoteFilename); + + /// <summary> + /// Requests that a share scan is performed. + /// </summary> + void RequestScan(); /// <summary> /// Searches the cache for the specified <paramref name="query"/> and returns the matching files. 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 file="ShareConnectionStringFactory.cs" company="slskd Team"> -// 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/. -// </copyright> - -namespace slskd.Shares -{ - using System; - - /// <summary> - /// Creates connection strings for share cache databases. - /// </summary> - public class ShareConnectionStringFactory - { - /// <summary> - /// Initializes a new instance of the <see cref="ShareConnectionStringFactory"/> class. - /// </summary> - /// <param name="createFromFile">The function used to create a connection string for a share cache database.</param> - /// <param name="createFromMemory">The function used to create an in-memory connection string for a share cache database.</param> - /// <param name="createBackupFromFile">The function used to crate a connection string for a share cache backup database.</param> - public ShareConnectionStringFactory( - Func<string, string> createFromFile, - Func<string, string> createFromMemory, - Func<string, string> createBackupFromFile) - { - CreateFromFile = createFromFile; - CreateFromMemory = createFromMemory; - CreateBackupFromFile = createBackupFromFile; - } - - /// <summary> - /// Gets a function used to create a connection string for a share cache database. - /// </summary> - public Func<string, string> CreateFromFile { get; } - - /// <summary> - /// Gets a function used to create an in-memory connection string for a share cache database. - /// </summary> - public Func<string, string> CreateFromMemory { get; } - - /// <summary> - /// Gets a function used to create a connection string for a share cache backup database. - /// </summary> - public Func<string, string> 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 file="ShareRepositoryFactory.cs" company="slskd Team"> +// 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/. +// </copyright> + +using System.IO; + +namespace slskd.Shares +{ + /// <summary> + /// Persistent storage of a shared file cache. + /// </summary> + public class SqliteShareRepositoryFactory : IShareRepositoryFactory + { + /// <summary> + /// Initializes a new instance of the <see cref="SqliteShareRepositoryFactory"/> class. + /// </summary> + /// <param name="optionsAtStartup"></param> + public SqliteShareRepositoryFactory( + OptionsAtStartup optionsAtStartup) + { + StorageMode = optionsAtStartup.Shares.Cache.StorageMode.ToEnum<StorageMode>(); + } + + private StorageMode StorageMode { get; } + + /// <summary> + /// Create a repository for the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the agent.</param> + /// <returns>The created repository.</returns> + 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"); + } + + /// <summary> + /// Create a repository backup for the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the agent.</param> + /// <returns>The created repository.</returns> + public IShareRepository CreateFromHostBackup(string name) + { + var file = Path.Combine(Program.DataDirectory, $"shares.{name}.bak.db"); + return new SqliteShareRepository($"Data Source={file}"); + } + + /// <summary> + /// Create a repository for the specified <paramref name="filename"/>. + /// </summary> + /// <param name="filename">The fully qualified path of the filename.</param> + /// <returns>The created repository.</returns> + 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 /// <param name="soulseekFileFactory"></param> public ShareScanner( int workerCount, - IReadWriteShareRepository shareRepository, + IShareRepository shareRepository, ISoulseekFileFactory soulseekFileFactory = null) { WorkerCount = workerCount; @@ -87,7 +87,7 @@ namespace slskd.Shares private IManagedState<SharedFileCacheState> State { get; } = new ManagedState<SharedFileCacheState>(); private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1); private CancellationTokenSource CancellationTokenSource { get; set; } - private IReadWriteShareRepository Repository { get; } + private IShareRepository Repository { get; } /// <summary> /// Scans the configured shares and fills the cache. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 12131eae..88105a8f 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -37,32 +37,22 @@ namespace slskd.Shares /// <summary> /// Initializes a new instance of the <see cref="ShareService"/> class. /// </summary> - /// <param name="shareConnectionStringFactory"></param> + /// <param name="shareRepositoryFactory"></param> /// <param name="optionsMonitor"></param> /// <param name="scanner"></param> public ShareService( - ShareConnectionStringFactory shareConnectionStringFactory, + IShareRepositoryFactory shareRepositoryFactory, IOptionsMonitor<Options> optionsMonitor, IShareScanner scanner = null) { var options = optionsMonitor.CurrentValue; - ConnectionStringFactory = shareConnectionStringFactory; CacheStorageMode = options.Shares.Cache.StorageMode.ToEnum<StorageMode>(); - 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 host = new Host("local"); + var repository = ShareRepositoryFactory.CreateFromHost(host.Name); Local = (host, repository); @@ -104,13 +94,16 @@ namespace slskd.Shares public IReadOnlyList<Host> Hosts => HostDictionary.Values.Select(v => v.Host).Prepend(Local.Host).ToList().AsReadOnly(); /// <summary> + /// Gets the local share host. + /// </summary> + public Host LocalHost => Local.Host; + + /// <summary> /// Gets the state monitor for the service. /// </summary> public IStateMonitor<ShareState> 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<Options> OptionsMonitor { get; } @@ -119,7 +112,7 @@ namespace slskd.Shares private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private StorageMode CacheStorageMode { get; } private ILogger Log { get; } = Serilog.Log.ForContext<ShareService>(); - private (Host Host, IReadWriteShareRepository Repository) Local { get; set; } + private (Host Host, IShareRepository Repository) Local { get; set; } private IEnumerable<IShareRepository> AllRepositories { get; set; } /// <summary> @@ -128,13 +121,14 @@ namespace slskd.Shares /// <param name="host">The host to add or update.</param> 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 - .Where(value => value.Host.State == HostState.Online) .Select(value => value.Repository) .Prepend(Local.Repository); } @@ -192,6 +186,43 @@ namespace slskd.Shares } /// <summary> + /// Dumps the local share cache to a file. + /// </summary> + /// <param name="filename">The destination file.</param> + /// <returns>The operation context.</returns> + public Task DumpAsync(string filename) + { + Local.Repository.DumpTo(filename); + return Task.CompletedTask; + } + + /// <summary> + /// Returns the share host with the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the host.</param> + /// <param name="host">The host, if found.</param> + /// <returns>A value indicating whether the host was found.</returns> + public bool TryGetHost(string name, out Host host) + { + if (HostDictionary.TryGetValue(name, out var record)) + { + host = record.Host; + return true; + } + + host = null; + return false; + } + + /// <summary> + /// Removes the share host with the specified <paramref name="name"/>. + /// </summary> + /// <param name="name">The name of the host.</param> + /// <returns>A value indicating whether the host was removed.</returns> + public bool TryRemoveHost(string name) + => HostDictionary.TryRemove(name, out _); + + /// <summary> /// Returns the contents of the specified <paramref name="directory"/>. /// </summary> /// <param name="directory">The directory for which the contents are to be listed.</param> @@ -214,27 +245,39 @@ namespace slskd.Shares /// <exception cref="NotFoundException"> /// Thrown when the specified remote filename can not be associated with a configured share. /// </exception> - public Task<FileInfo> 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; + + resolvedFilename = Local.Repository.FindFilename(remoteFilename.LocalizePath()); - if (string.IsNullOrEmpty(resolvedFilename)) + if (!string.IsNullOrEmpty(resolvedFilename)) { - throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a local file"); + return Task.FromResult((resolvedHost, resolvedFilename)); } - var fileInfo = new FileInfo(resolvedFilename); - - if (!fileInfo.Exists) + // 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) { - // 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."); + resolvedFilename = host.Repository.FindFilename(remoteFilename.LocalizePath()); + + if (!string.IsNullOrEmpty(resolvedFilename)) + { + return Task.FromResult((host.Host.Name, resolvedFilename)); + } } - return Task.FromResult(fileInfo); + throw new NotFoundException($"The requested filename '{remoteFilename}' could not be resolved to a physical file"); + } + + /// <summary> + /// Requests that a share scan is performed. + /// </summary> + public void RequestScan() + { + State.SetValue(state => state with { ScanPending = true }); } /// <summary> @@ -264,7 +307,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(Local.Host.Name)); Log.Debug("Shared file cache database backup complete"); } @@ -311,11 +354,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(Local.Host.Name); + + 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"); } @@ -329,7 +374,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 } @@ -337,11 +382,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(Local.Host.Name); + + 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"); } @@ -409,9 +456,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 diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 28788c3f..0a71280d 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -28,7 +28,7 @@ namespace slskd.Shares /// <summary> /// Persistent storage of shared files and metadata. /// </summary> - public class SqliteShareRepository : IReadWriteShareRepository + public class SqliteShareRepository : IShareRepository { /// <summary> /// Initializes a new instance of the <see cref="SqliteShareRepository"/> class. @@ -47,84 +47,13 @@ namespace slskd.Shares private ILogger Log { get; } = Serilog.Log.ForContext<SqliteShareRepository>(); /// <summary> - /// Attempts to validate the database at the specified <paramref name="connectionString"/>, or the - /// default <see cref="ConnectionString"/>. + /// Backs the current database up to the database at the specified <paramref name="repository"/>. /// </summary> - /// <param name="connectionString">The connection string of the database to validate.</param> - /// <returns>A value indicating whether the database is valid.</returns> - 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<string, string>() - { - { "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; - } - } - - /// <summary> - /// Backs the current database up to the database at the specified <paramref name="connectionString"/>. - /// </summary> - /// <param name="connectionString">The connection string of the destination database.</param> - public void BackupTo(string connectionString) + /// <param name="repository">The destination repository.</param> + public void BackupTo(IShareRepository repository) { using var sourceConn = GetConnection(ConnectionString); - using var backupConn = GetConnection(connectionString); + using var backupConn = GetConnection(repository.ConnectionString); sourceConn.BackupDatabase(backupConn); } @@ -225,6 +154,19 @@ namespace slskd.Shares } /// <summary> + /// Dumps the contents of the database to a file. + /// </summary> + /// <param name="filename">The destination file.</param> + public void DumpTo(string filename) + { + using var sourceConn = GetConnection(ConnectionString); + + // 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); + } + + /// <summary> /// Finds the filename of the file matching the specified <paramref name="maskedFilename"/>. /// </summary> /// <param name="maskedFilename">The fully qualified remote path of the file.</param> @@ -442,12 +384,12 @@ namespace slskd.Shares } /// <summary> - /// Restores the current database from the database at the specified <paramref name="connectionString"/>. + /// Restores the current database from the database at the specified <paramref name="repository"/>. /// </summary> - /// <param name="connectionString">The connection string of the source database.</param> - public void RestoreFrom(string connectionString) + /// <param name="repository">The destination repository.</param> + public void RestoreFrom(IShareRepository repository) { - using var sourceConn = GetConnection(connectionString); + using var sourceConn = GetConnection(repository.ConnectionString); using var restoreConn = GetConnection(); sourceConn.BackupDatabase(restoreConn); } @@ -505,6 +447,87 @@ namespace slskd.Shares } /// <summary> + /// Attempts to validate the backing database. + /// </summary> + /// <returns>A value indicating whether the database is valid.</returns> + public bool TryValidate() + { + return TryValidate(out _); + } + + /// <summary> + /// Attempts to validate the backing database. + /// </summary> + /// <param name="problems">The list of problems, if the database is invalid.</param> + /// <returns>A value indicating whether the database is valid.</returns> + public bool TryValidate(out IEnumerable<string> problems) + { + var list = new List<string>(); + 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<string, string>() + { + { "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; + } + } + + /// <summary> /// Updates the scan started at the specified <paramref name="timestamp"/> to set the <paramref name="end"/>. /// </summary> /// <param name="timestamp">The timestamp associated with the scan.</param> 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 <see cref="Host"/> class. /// </summary> /// <param name="name">The name of the host.</param> - /// <param name="type">The type of the host.</param> /// <param name="shares">The collection of hosted shares.</param> - /// <param name="state">The initial state of the host.</param> - public Host(string name, HostType type, IEnumerable<Share> shares = null, HostState state = HostState.Offline) + public Host(string name, IEnumerable<Share> shares = null) { Name = name; - Type = type; Shares = shares ?? Enumerable.Empty<Share>(); - State = state; } /// <summary> /// Gets the name of the host. /// </summary> - /// <remarks>Corresponds to the configured <see cref="Options.InstanceName"/> of the host.</remarks> + /// <remarks>Corresponds to the configured <see cref="Options.InstanceName"/> of the host, or "local" for the local host.</remarks> public string Name { get; } /// <summary> /// Gets the collection of hosted shares. /// </summary> public IEnumerable<Share> Shares { get; init; } - - /// <summary> - /// Gets the host state. - /// </summary> - public HostState State { get; init; } - - /// <summary> - /// Gets the host type. - /// </summary> - 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 file="HostState.cs" company="slskd Team"> -// 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/. -// </copyright> - -namespace slskd.Shares -{ - /// <summary> - /// The state of a share host. - /// </summary> - public enum HostState - { - /// <summary> - /// Offline; unable to service requests. - /// </summary> - Offline = 0, - - /// <summary> - /// Online; able to service requests. - /// </summary> - Online = 1, - } -} 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/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 /// <param name="username">The username associated with the file.</param> /// <param name="filename">The filename of the file for which the position is to be estimated.</param> /// <returns>The estimated queue position of the file.</returns> - /// <exception cref="FileNotFoundException">Thrown if the specified filename is not enqueued.</exception> + /// <exception cref="NotFoundException">Thrown if the specified filename is not enqueued.</exception> int EstimatePosition(string username, string filename); /// <summary> @@ -251,7 +251,7 @@ namespace slskd.Transfers /// <param name="username">The username associated with the file.</param> /// <param name="filename">The filename of the file for which the position is to be estimated.</param> /// <returns>The estimated queue position of the file.</returns> - /// <exception cref="FileNotFoundException">Thrown if the specified filename is not enqueued.</exception> + /// <exception cref="NotFoundException">Thrown if the specified filename is not enqueued.</exception> 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; diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index f98378e9..40718af7 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.Network; using slskd.Shares; using slskd.Users; @@ -43,11 +44,13 @@ namespace slskd.Transfers.Uploads ISoulseekClient soulseekClient, IOptionsMonitor<Options> optionsMonitor, IShareService shareService, + INetworkService networkService, IDbContextFactory<TransfersDbContext> contextFactory) { Users = userService; Client = soulseekClient; Shares = shareService; + Network = networkService; ContextFactory = contextFactory; OptionsMonitor = optionsMonitor; @@ -72,6 +75,7 @@ namespace slskd.Transfers.Uploads private IShareService Shares { get; set; } private IUserService Users { get; set; } private IOptionsMonitor<Options> OptionsMonitor { get; } + private INetworkService Network { get; } /// <summary> /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. @@ -107,13 +111,42 @@ namespace slskd.Transfers.Uploads /// <returns>The operation context.</returns> public async Task EnqueueAsync(string username, string filename) { - FileInfo fileInfo = default; + string host = default; + string localFilename = default; + long localFileLength = default; Log.Information("[{Context}] {Username} requested {Filename}", "UPLOAD REQUESTED", username, filename); try { - fileInfo = await Shares.ResolveFileAsync(filename.LocalizePath()); + (host, localFilename) = await Shares.ResolveFileAsync(filename.LocalizePath()); + + 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. + 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 + { + 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) { @@ -121,13 +154,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 == fileInfo.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", fileInfo.FullName, username); + Log.Information("Upload {Filename} to {Username} is already queued or in progress", localFilename, username); return; } @@ -138,8 +173,8 @@ namespace slskd.Transfers.Uploads Id = id, Username = username, Direction = TransferDirection.Upload, - Filename = fileInfo.FullName, - Size = fileInfo.Length, + Filename = localFilename, + Size = localFileLength, StartOffset = 0, // potentially updated later during handshaking RequestedAt = DateTime.UtcNow, }; @@ -184,7 +219,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}", localFilename, username, args.PreviousState, args.Transfer.State); if (Application.IsShuttingDown) { @@ -210,25 +245,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); - var completedTransfer = await Client.UploadAsync( - username, - filename, - fileInfo.FullName, - options: topts, - cancellationToken: cts.Token); + if (host == "local") + { + var completedTransfer = await Client.UploadAsync( + username, + filename, + size: localFileLength, + inputStreamFactory: () => Task.FromResult((Stream)new FileStream(localFilename, FileMode.Open, FileAccess.Read)), + options: topts, + cancellationToken: cts.Token); + + transfer = transfer.WithSoulseekTransfer(completedTransfer); + } + else + { + TaskCompletionSource uploadCompletion = default; + + 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 // beyond this point, which may overwrite the final state rateLimiter.Dispose(); - transfer = transfer.WithSoulseekTransfer(completedTransfer); - // todo: broadcast SynchronizedUpdate(transfer, cancellable: false); } diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index f1c7204e..f496703c 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -46,6 +46,7 @@ <PackageReference Include="IPAddressRange" Version="4.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.7" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.0.0" /> + <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="6.0.9" /> <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> @@ -65,7 +66,7 @@ <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" /> <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="7.1.1" /> <PackageReference Include="Serilog.Sinks.Http" Version="8.0.0" /> - <PackageReference Include="Soulseek" Version="5.1.5" /> + <PackageReference Include="Soulseek" Version="6.0.0-pre.1" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.354"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> |
