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/slskd/Common | |
| 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/slskd/Common')
| -rw-r--r-- | src/slskd/Common/CommonExtensions.cs | 21 | ||||
| -rw-r--r-- | src/slskd/Common/Cryptography/Aes.cs | 112 | ||||
| -rw-r--r-- | src/slskd/Common/Cryptography/Base62Extensions.cs | 215 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/NetworkException.cs | 72 | ||||
| -rw-r--r-- | src/slskd/Common/Retry.cs | 16 |
5 files changed, 411 insertions, 25 deletions
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(); |
