From 5ce2af04031d4c6fd1f057226cd11598434d5c69 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Mar 2023 10:53:22 -0500 Subject: move Base62Extensions, add Base64Extensions --- src/slskd/Common/Base62Extensions.cs | 215 ++++++++++++++++++++++ src/slskd/Common/Base64Extensions.cs | 48 +++++ src/slskd/Common/Cryptography/Base62Extensions.cs | 215 ---------------------- 3 files changed, 263 insertions(+), 215 deletions(-) create mode 100644 src/slskd/Common/Base62Extensions.cs create mode 100644 src/slskd/Common/Base64Extensions.cs delete mode 100644 src/slskd/Common/Cryptography/Base62Extensions.cs (limited to 'src') diff --git a/src/slskd/Common/Base62Extensions.cs b/src/slskd/Common/Base62Extensions.cs new file mode 100644 index 00000000..b0171299 --- /dev/null +++ b/src/slskd/Common/Base62Extensions.cs @@ -0,0 +1,215 @@ +/* + The MIT License (MIT) + + Copyright (c) 2016 - 2020 JoyMoe Interactive Entertainment Limited + + All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + + https://github.com/JoyMoe/Base62.Net + */ +// -- suppress analysis + +namespace slskd +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text; + + public static class Base62Extensions + { + private const string DefaultCharacterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + private const string InvertedCharacterSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + /// + /// Encode a 2-byte number with Base62 + /// + /// String + /// Use inverted character set + /// Base62 string + public static string ToBase62(this short original, bool inverted = false) + { + var array = BitConverter.GetBytes(original); + + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return array.ToBase62(inverted); + } + + /// + /// Encode a 4-byte number with Base62 + /// + /// String + /// Use inverted character set + /// Base62 string + public static string ToBase62(this int original, bool inverted = false) + { + var array = BitConverter.GetBytes(original); + + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return array.ToBase62(inverted); + } + + /// + /// Encode a 8-byte number with Base62 + /// + /// String + /// Use inverted character set + /// Base62 string + public static string ToBase62(this long original, bool inverted = false) + { + var array = BitConverter.GetBytes(original); + + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return array.ToBase62(inverted); + } + + /// + /// Encode a string with Base62 + /// + /// String + /// Use inverted character set + /// Base62 string + public static string ToBase62(this string original, bool inverted = false) + { + return Encoding.UTF8.GetBytes(original).ToBase62(inverted); + } + + /// + /// Encode a byte array with Base62 + /// + /// Byte array + /// Use inverted character set + /// Base62 string + public static string ToBase62(this byte[] original, bool inverted = false) + { + var characterSet = inverted ? InvertedCharacterSet : DefaultCharacterSet; + var arr = Array.ConvertAll(original, t => (int)t); + + var converted = BaseConvert(arr, 256, 62); + var builder = new StringBuilder(); + foreach (var t in converted) + { + builder.Append(characterSet[t]); + } + return builder.ToString(); + } + + /// + /// Decode a base62-encoded string + /// + /// Base62 string + /// Use inverted character set + /// Byte array + public static T FromBase62(this string base62, bool inverted = false) + { + var array = base62.FromBase62(inverted); + + switch (Type.GetTypeCode(typeof(T))) + { + case TypeCode.String: + return (T)Convert.ChangeType(Encoding.UTF8.GetString(array), typeof(T), CultureInfo.InvariantCulture); + case TypeCode.Int16: + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return (T)Convert.ChangeType(BitConverter.ToInt16(array, 0), typeof(T), CultureInfo.InvariantCulture); + case TypeCode.Int32: + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return (T)Convert.ChangeType(BitConverter.ToInt32(array, 0), typeof(T), CultureInfo.InvariantCulture); + case TypeCode.Int64: + if (BitConverter.IsLittleEndian) + { + Array.Reverse(array); + } + + return (T)Convert.ChangeType(BitConverter.ToInt64(array, 0), typeof(T), CultureInfo.InvariantCulture); + default: + throw new Exception($"Type of {typeof(T)} does not support."); + } + } + + /// + /// Decode a base62-encoded string + /// + /// Base62 string + /// Use inverted character set + /// Byte array + public static byte[] FromBase62(this string base62, bool inverted = false) + { + if (string.IsNullOrWhiteSpace(base62)) + { + throw new ArgumentNullException(nameof(base62)); + } + + var characterSet = inverted ? InvertedCharacterSet : DefaultCharacterSet; + var arr = Array.ConvertAll(base62.ToCharArray(), characterSet.IndexOf); + + var converted = BaseConvert(arr, 62, 256); + return Array.ConvertAll(converted, Convert.ToByte); + } + + private static int[] BaseConvert(int[] source, int sourceBase, int targetBase) + { + var result = new List(); + var leadingZeroCount = Math.Min(source.TakeWhile(x => x == 0).Count(), source.Length - 1); + int count; + while ((count = source.Length) > 0) + { + var quotient = new List(); + var remainder = 0; + for (var i = 0; i != count; i++) + { + var accumulator = source[i] + remainder * sourceBase; + var digit = accumulator / targetBase; + remainder = accumulator % targetBase; + if (quotient.Count > 0 || digit > 0) + { + quotient.Add(digit); + } + } + + result.Insert(0, remainder); + source = quotient.ToArray(); + } + result.InsertRange(0, Enumerable.Repeat(0, leadingZeroCount)); + return result.ToArray(); + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/Base64Extensions.cs b/src/slskd/Common/Base64Extensions.cs new file mode 100644 index 00000000..6eaf2dff --- /dev/null +++ b/src/slskd/Common/Base64Extensions.cs @@ -0,0 +1,48 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Text; + + /// + /// Base 64 extensions. + /// + public static class Base64Extensions + { + /// + /// Encode this string in Base 64. + /// + /// The string to encode. + /// The encoded string. + public static string ToBase64(this string str) + { + return Convert.ToBase64String(Encoding.UTF8.GetBytes(str)); + } + + /// + /// Decode this string from Base 64. + /// + /// The string to decode. + /// The decoded string. + public static string FromBase64(this string str) + { + return Encoding.UTF8.GetString(Convert.FromBase64String(str)); + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/Cryptography/Base62Extensions.cs b/src/slskd/Common/Cryptography/Base62Extensions.cs deleted file mode 100644 index b9ab3a72..00000000 --- a/src/slskd/Common/Cryptography/Base62Extensions.cs +++ /dev/null @@ -1,215 +0,0 @@ -/* - The MIT License (MIT) - - Copyright (c) 2016 - 2020 JoyMoe Interactive Entertainment Limited - - All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - - https://github.com/JoyMoe/Base62.Net - */ -// -- suppress analysis - -namespace slskd.Cryptography -{ - using System; - using System.Collections.Generic; - using System.Globalization; - using System.Linq; - using System.Text; - - public static class Base62Extensions - { - private const string DefaultCharacterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; - private const string InvertedCharacterSet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - - /// - /// Encode a 2-byte number with Base62 - /// - /// String - /// Use inverted character set - /// Base62 string - public static string ToBase62(this short original, bool inverted = false) - { - var array = BitConverter.GetBytes(original); - - if (BitConverter.IsLittleEndian) - { - Array.Reverse(array); - } - - return array.ToBase62(inverted); - } - - /// - /// Encode a 4-byte number with Base62 - /// - /// String - /// Use inverted character set - /// Base62 string - public static string ToBase62(this int original, bool inverted = false) - { - var array = BitConverter.GetBytes(original); - - if (BitConverter.IsLittleEndian) - { - Array.Reverse(array); - } - - return array.ToBase62(inverted); - } - - /// - /// Encode a 8-byte number with Base62 - /// - /// String - /// Use inverted character set - /// Base62 string - public static string ToBase62(this long original, bool inverted = false) - { - var array = BitConverter.GetBytes(original); - - if (BitConverter.IsLittleEndian) - { - Array.Reverse(array); - } - - return array.ToBase62(inverted); - } - - /// - /// Encode a string with Base62 - /// - /// String - /// Use inverted character set - /// Base62 string - public static string ToBase62(this string original, bool inverted = false) - { - return Encoding.UTF8.GetBytes(original).ToBase62(inverted); - } - - /// - /// Encode a byte array with Base62 - /// - /// Byte array - /// Use inverted character set - /// Base62 string - public static string ToBase62(this byte[] original, bool inverted = false) - { - var characterSet = inverted ? InvertedCharacterSet : DefaultCharacterSet; - var arr = Array.ConvertAll(original, t => (int)t); - - var converted = BaseConvert(arr, 256, 62); - var builder = new StringBuilder(); - foreach (var t in converted) - { - builder.Append(characterSet[t]); - } - return builder.ToString(); - } - - /// - /// Decode a base62-encoded string - /// - /// Base62 string - /// Use inverted character set - /// Byte array - public static T FromBase62(this string base62, bool inverted = false) - { - var array = base62.FromBase62(inverted); - - switch (Type.GetTypeCode(typeof(T))) - { - case TypeCode.String: - return (T)Convert.ChangeType(Encoding.UTF8.GetString(array), typeof(T), CultureInfo.InvariantCulture); - case TypeCode.Int16: - if (BitConverter.IsLittleEndian) - { - Array.Reverse(array); - } - - return (T)Convert.ChangeType(BitConverter.ToInt16(array, 0), typeof(T), CultureInfo.InvariantCulture); - case TypeCode.Int32: - if (BitConverter.IsLittleEndian) - { - Array.Reverse(array); - } - - return (T)Convert.ChangeType(BitConverter.ToInt32(array, 0), typeof(T), CultureInfo.InvariantCulture); - case TypeCode.Int64: - if (BitConverter.IsLittleEndian) - { - Array.Reverse(array); - } - - return (T)Convert.ChangeType(BitConverter.ToInt64(array, 0), typeof(T), CultureInfo.InvariantCulture); - default: - throw new Exception($"Type of {typeof(T)} does not support."); - } - } - - /// - /// Decode a base62-encoded string - /// - /// Base62 string - /// Use inverted character set - /// Byte array - public static byte[] FromBase62(this string base62, bool inverted = false) - { - if (string.IsNullOrWhiteSpace(base62)) - { - throw new ArgumentNullException(nameof(base62)); - } - - var characterSet = inverted ? InvertedCharacterSet : DefaultCharacterSet; - var arr = Array.ConvertAll(base62.ToCharArray(), characterSet.IndexOf); - - var converted = BaseConvert(arr, 62, 256); - return Array.ConvertAll(converted, Convert.ToByte); - } - - private static int[] BaseConvert(int[] source, int sourceBase, int targetBase) - { - var result = new List(); - var leadingZeroCount = Math.Min(source.TakeWhile(x => x == 0).Count(), source.Length - 1); - int count; - while ((count = source.Length) > 0) - { - var quotient = new List(); - var remainder = 0; - for (var i = 0; i != count; i++) - { - var accumulator = source[i] + remainder * sourceBase; - var digit = accumulator / targetBase; - remainder = accumulator % targetBase; - if (quotient.Count > 0 || digit > 0) - { - quotient.Add(digit); - } - } - - result.Insert(0, remainder); - source = quotient.ToArray(); - } - result.InsertRange(0, Enumerable.Repeat(0, leadingZeroCount)); - return result.ToArray(); - } - } -} \ No newline at end of file -- cgit v1.2.3 From b09f3a9a1b023064ed3dd7bf4f624a5669b7a47e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Mar 2023 10:54:04 -0500 Subject: base64 encode the X-Relay-Filename header (and append Base64) --- src/slskd/Relay/API/Controllers/RelayController.cs | 3 ++- src/slskd/Relay/RelayClient.cs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index 49c76e2d..a7ed7e2d 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -31,6 +31,7 @@ namespace slskd.Relay using Microsoft.AspNetCore.WebUtilities; using Microsoft.Net.Http.Headers; using Serilog; + using slskd.Cryptography; using slskd.Shares; /// @@ -118,7 +119,7 @@ namespace slskd.Relay var agentName = Request.Headers["X-Relay-Agent"].FirstOrDefault(); var credential = Request.Headers["X-Relay-Credential"].FirstOrDefault(); - var filename = Request.Headers["X-Relay-Filename"].FirstOrDefault(); + var filename = Request.Headers["X-Relay-Filename-Base64"].FirstOrDefault()?.FromBase64(); if (!Relay.RegisteredAgents.Any(a => a.Name == agentName) || string.IsNullOrEmpty(credential)) { diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index eef84c27..f3880c97 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -457,7 +457,7 @@ namespace slskd.Relay request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey); request.Headers.Add("X-Relay-Agent", OptionsMonitor.CurrentValue.InstanceName); request.Headers.Add("X-Relay-Credential", ComputeCredential(token)); - request.Headers.Add("X-Relay-Filename", filename); + request.Headers.Add("X-Relay-Filename-Base64", filename.ToBase64()); using var client = CreateHttpClient(); using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); -- cgit v1.2.3