From e56275fb46296781798a9af4a42fc3fb623c15cd Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Mon, 3 Jul 2023 21:51:36 +0200 Subject: [PATCH] Extract networking constants --- Emby.Dlna/Main/DlnaEntryPoint.cs | 1 + .../EntryPoints/UdpServerEntryPoint.cs | 1 + Jellyfin.Networking/Constants/Network.cs | 75 ++++ .../Extensions/NetworkExtensions.cs | 351 ++++++++++++++++++ Jellyfin.Networking/Manager/NetworkManager.cs | 36 +- .../ApiServiceCollectionExtensions.cs | 19 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 350 ----------------- .../NetworkExtensionsTests.cs | 2 +- .../NetworkParseTests.cs | 2 +- 9 files changed, 459 insertions(+), 378 deletions(-) create mode 100644 Jellyfin.Networking/Constants/Network.cs create mode 100644 Jellyfin.Networking/Extensions/NetworkExtensions.cs delete mode 100644 MediaBrowser.Common/Net/NetworkExtensions.cs diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index f6ec9574b..1a4bec398 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -11,6 +11,7 @@ using System.Threading.Tasks; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; using Jellyfin.Networking.Configuration; +using Jellyfin.Networking.Extensions; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 2839e163e..54191649d 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -7,6 +7,7 @@ using System.Threading; using System.Threading.Tasks; using Emby.Server.Implementations.Udp; using Jellyfin.Networking.Configuration; +using Jellyfin.Networking.Extensions; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller; diff --git a/Jellyfin.Networking/Constants/Network.cs b/Jellyfin.Networking/Constants/Network.cs new file mode 100644 index 000000000..7fadc74bb --- /dev/null +++ b/Jellyfin.Networking/Constants/Network.cs @@ -0,0 +1,75 @@ +using System.Net; +using Microsoft.AspNetCore.HttpOverrides; + +namespace Jellyfin.Networking.Constants; + +/// +/// Networking constants. +/// +public static class Network +{ + /// + /// IPv4 mask bytes. + /// + public const int IPv4MaskBytes = 4; + + /// + /// IPv6 mask bytes. + /// + public const int IPv6MaskBytes = 16; + + /// + /// Minimum IPv4 prefix size. + /// + public const int MinimumIPv4PrefixSize = 32; + + /// + /// Minimum IPv6 prefix size. + /// + public const int MinimumIPv6PrefixSize = 128; + + /// + /// Whole IPv4 address space. + /// + public static readonly IPNetwork IPv4Any = new IPNetwork(IPAddress.Any, 0); + + /// + /// Whole IPv6 address space. + /// + public static readonly IPNetwork IPv6Any = new IPNetwork(IPAddress.IPv6Any, 0); + + /// + /// IPv4 Loopback as defined in RFC 5735. + /// + public static readonly IPNetwork IPv4RFC5735Loopback = new IPNetwork(IPAddress.Loopback, 8); + + /// + /// IPv4 private class A as defined in RFC 1918. + /// + public static readonly IPNetwork IPv4RFC1918PrivateClassA = new IPNetwork(IPAddress.Parse("10.0.0.0"), 8); + + /// + /// IPv4 private class B as defined in RFC 1918. + /// + public static readonly IPNetwork IPv4RFC1918PrivateClassB = new IPNetwork(IPAddress.Parse("172.16.0.0"), 12); + + /// + /// IPv4 private class C as defined in RFC 1918. + /// + public static readonly IPNetwork IPv4RFC1918PrivateClassC = new IPNetwork(IPAddress.Parse("192.168.0.0"), 16); + + /// + /// IPv6 loopback as defined in RFC 4291. + /// + public static readonly IPNetwork IPv6RFC4291Loopback = new IPNetwork(IPAddress.IPv6Loopback, 128); + + /// + /// IPv6 site local as defined in RFC 4291. + /// + public static readonly IPNetwork IPv6RFC4291SiteLocal = new IPNetwork(IPAddress.Parse("fe80::"), 10); + + /// + /// IPv6 unique local as defined in RFC 4193. + /// + public static readonly IPNetwork IPv6RFC4193UniqueLocal = new IPNetwork(IPAddress.Parse("fc00::"), 7); +} diff --git a/Jellyfin.Networking/Extensions/NetworkExtensions.cs b/Jellyfin.Networking/Extensions/NetworkExtensions.cs new file mode 100644 index 000000000..2ad6bae62 --- /dev/null +++ b/Jellyfin.Networking/Extensions/NetworkExtensions.cs @@ -0,0 +1,351 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text.RegularExpressions; +using Jellyfin.Extensions; +using Jellyfin.Networking.Constants; +using Microsoft.AspNetCore.HttpOverrides; + +namespace Jellyfin.Networking.Extensions; + +/// +/// Defines the . +/// +public static partial class NetworkExtensions +{ + // Use regular expression as CheckHostName isn't RFC5892 compliant. + // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation + [GeneratedRegex(@"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$", RegexOptions.IgnoreCase, "en-US")] + private static partial Regex fqdnGeneratedRegex(); + + /// + /// Returns true if the IPAddress contains an IP6 Local link address. + /// + /// IPAddress object to check. + /// True if it is a local link address. + /// + /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress + /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. + /// + public static bool IsIPv6LinkLocal(IPAddress address) + { + ArgumentNullException.ThrowIfNull(address); + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + if (address.AddressFamily != AddressFamily.InterNetworkV6) + { + return false; + } + + // GetAddressBytes + Span octet = stackalloc byte[16]; + address.TryWriteBytes(octet, out _); + uint word = (uint)(octet[0] << 8) + octet[1]; + + return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link. + } + + /// + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// + /// Subnet mask in CIDR notation. + /// IPv4 or IPv6 family. + /// String value of the subnet mask in dotted decimal notation. + public static IPAddress CidrToMask(byte cidr, AddressFamily family) + { + uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? Network.MinimumIPv4PrefixSize : Network.MinimumIPv6PrefixSize) - cidr); + addr = ((addr & 0xff000000) >> 24) + | ((addr & 0x00ff0000) >> 8) + | ((addr & 0x0000ff00) << 8) + | ((addr & 0x000000ff) << 24); + return new IPAddress(addr); + } + + /// + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// + /// Subnet mask in CIDR notation. + /// IPv4 or IPv6 family. + /// String value of the subnet mask in dotted decimal notation. + public static IPAddress CidrToMask(int cidr, AddressFamily family) + { + uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? Network.MinimumIPv4PrefixSize : Network.MinimumIPv6PrefixSize) - cidr); + addr = ((addr & 0xff000000) >> 24) + | ((addr & 0x00ff0000) >> 8) + | ((addr & 0x0000ff00) << 8) + | ((addr & 0x000000ff) << 24); + return new IPAddress(addr); + } + + /// + /// Convert a subnet mask to a CIDR. IPv4 only. + /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. + /// + /// Subnet mask. + /// Byte CIDR representing the mask. + public static byte MaskToCidr(IPAddress mask) + { + ArgumentNullException.ThrowIfNull(mask); + + byte cidrnet = 0; + if (mask.Equals(IPAddress.Any)) + { + return cidrnet; + } + + // GetAddressBytes + Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? Network.IPv4MaskBytes : Network.IPv6MaskBytes]; + if (!mask.TryWriteBytes(bytes, out var bytesWritten)) + { + Console.WriteLine("Unable to write address bytes, only {bytesWritten} bytes written."); + } + + var zeroed = false; + for (var i = 0; i < bytes.Length; i++) + { + for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1) + { + if (zeroed) + { + // Invalid netmask. + return (byte)~cidrnet; + } + + if ((v & 0x80) == 0) + { + zeroed = true; + } + else + { + cidrnet++; + } + } + } + + return cidrnet; + } + + /// + /// Converts an IPAddress into a string. + /// IPv6 addresses are returned in [ ], with their scope removed. + /// + /// Address to convert. + /// URI safe conversion of the address. + public static string FormatIPString(IPAddress? address) + { + if (address is null) + { + return string.Empty; + } + + var str = address.ToString(); + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + int i = str.IndexOf('%', StringComparison.Ordinal); + if (i != -1) + { + str = str.Substring(0, i); + } + + return $"[{str}]"; + } + + return str; + } + + /// + /// Try parsing an array of strings into objects, respecting exclusions. + /// Elements without a subnet mask will be represented as with a single IP. + /// + /// Input string array to be parsed. + /// Collection of . + /// Boolean signaling if negated or not negated values should be parsed. + /// True if parsing was successful. + public static bool TryParseToSubnets(string[] values, [NotNullWhen(true)] out IReadOnlyList? result, bool negated = false) + { + if (values is null || values.Length == 0) + { + result = null; + return false; + } + + var tmpResult = new List(); + for (int a = 0; a < values.Length; a++) + { + if (TryParseToSubnet(values[a], out var innerResult, negated)) + { + tmpResult.Add(innerResult); + } + } + + result = tmpResult; + return tmpResult.Count > 0; + } + + /// + /// Try parsing a string into an , respecting exclusions. + /// Inputs without a subnet mask will be represented as with a single IP. + /// + /// Input string to be parsed. + /// An . + /// Boolean signaling if negated or not negated values should be parsed. + /// True if parsing was successful. + public static bool TryParseToSubnet(ReadOnlySpan value, [NotNullWhen(true)] out IPNetwork? result, bool negated = false) + { + var splitString = value.Trim().Split('/'); + if (splitString.MoveNext()) + { + var ipBlock = splitString.Current; + var address = IPAddress.None; + if (negated && ipBlock.StartsWith("!") && IPAddress.TryParse(ipBlock[1..], out var tmpAddress)) + { + address = tmpAddress; + } + else if (!negated && IPAddress.TryParse(ipBlock, out tmpAddress)) + { + address = tmpAddress; + } + + if (address != IPAddress.None) + { + if (splitString.MoveNext()) + { + var subnetBlock = splitString.Current; + if (int.TryParse(subnetBlock, out var netmask)) + { + result = new IPNetwork(address, netmask); + return true; + } + else if (IPAddress.TryParse(subnetBlock, out var netmaskAddress)) + { + result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + return true; + } + } + else if (address.AddressFamily == AddressFamily.InterNetwork) + { + result = new IPNetwork(address, Network.MinimumIPv4PrefixSize); + return true; + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + result = new IPNetwork(address, Network.MinimumIPv6PrefixSize); + return true; + } + } + } + + result = null; + return false; + } + + /// + /// Attempts to parse a host span. + /// + /// Host name to parse. + /// Object representing the span, if it has successfully been parsed. + /// true if IPv4 is enabled. + /// true if IPv6 is enabled. + /// true if the parsing is successful, false if not. + public static bool TryParseHost(ReadOnlySpan host, [NotNullWhen(true)] out IPAddress[]? addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) + { + if (host.IsEmpty) + { + addresses = null; + return false; + } + + host = host.Trim(); + + // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. + if (host[0] == '[') + { + int i = host.IndexOf(']'); + if (i != -1) + { + return TryParseHost(host[1..(i - 1)], out addresses); + } + + addresses = Array.Empty(); + return false; + } + + var hosts = new List(); + foreach (var splitSpan in host.Split(':')) + { + hosts.Add(splitSpan.ToString()); + } + + if (hosts.Count <= 2) + { + // Is hostname or hostname:port + if (fqdnGeneratedRegex().IsMatch(hosts[0])) + { + try + { + addresses = Dns.GetHostAddresses(hosts[0]); + return true; + } + catch (SocketException) + { + // Log and then ignore socket errors, as the result value will just be an empty array. + Console.WriteLine("GetHostAddresses failed."); + } + } + + // Is an IPv4 or IPv4:port + if (IPAddress.TryParse(hosts[0].AsSpan().LeftPart('/'), out var address)) + { + if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIPv4Enabled && isIPv6Enabled)) + || ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIPv4Enabled && !isIPv6Enabled))) + { + addresses = Array.Empty(); + return false; + } + + addresses = new[] { address }; + + // Host name is an IPv4 address, so fake resolve. + return true; + } + } + else if (hosts.Count > 0 && hosts.Count <= 9) // 8 octets + port + { + if (IPAddress.TryParse(host.LeftPart('/'), out var address)) + { + addresses = new[] { address }; + return true; + } + } + + addresses = Array.Empty(); + return false; + } + + /// + /// Gets the broadcast address for a . + /// + /// The . + /// The broadcast address. + public static IPAddress GetBroadcastAddress(IPNetwork network) + { + var addressBytes = network.Prefix.GetAddressBytes(); + if (BitConverter.IsLittleEndian) + { + addressBytes = addressBytes.Reverse().ToArray(); + } + + uint iPAddress = BitConverter.ToUInt32(addressBytes, 0); + uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0); + uint broadCastIPAddress = iPAddress | ~ipMaskV4; + + return new IPAddress(BitConverter.GetBytes(broadCastIPAddress)); + } +} diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index c80038e7d..f20e28526 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -8,6 +8,8 @@ using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using Jellyfin.Networking.Configuration; +using Jellyfin.Networking.Constants; +using Jellyfin.Networking.Extensions; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Model.Net; @@ -316,17 +318,17 @@ namespace Jellyfin.Networking.Manager var fallbackLanSubnets = new List(); if (IsIPv6Enabled) { - fallbackLanSubnets.Add(new IPNetwork(IPAddress.IPv6Loopback, 128)); // RFC 4291 (Loopback) - fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // RFC 4291 (Site local) - fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // RFC 4193 (Unique local) + fallbackLanSubnets.Add(Network.IPv6RFC4291Loopback); // RFC 4291 (Loopback) + fallbackLanSubnets.Add(Network.IPv6RFC4291SiteLocal); // RFC 4291 (Site local) + fallbackLanSubnets.Add(Network.IPv6RFC4193UniqueLocal); // RFC 4193 (Unique local) } if (IsIPv4Enabled) { - fallbackLanSubnets.Add(new IPNetwork(IPAddress.Loopback, 8)); // RFC 5735 (Loopback) - fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); // RFC 1918 (private) - fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("172.16.0.0"), 12)); // RFC 1918 (private) - fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("192.168.0.0"), 16)); // RFC 1918 (private) + fallbackLanSubnets.Add(Network.IPv4RFC5735Loopback); // RFC 5735 (Loopback) + fallbackLanSubnets.Add(Network.IPv4RFC1918PrivateClassA); // RFC 1918 (private Class A) + fallbackLanSubnets.Add(Network.IPv4RFC1918PrivateClassB); // RFC 1918 (private Class B) + fallbackLanSubnets.Add(Network.IPv4RFC1918PrivateClassC); // RFC 1918 (private Class C) } _lanSubnets = fallbackLanSubnets; @@ -369,12 +371,12 @@ namespace Jellyfin.Networking.Manager if (bindAddresses.Contains(IPAddress.Loopback)) { - interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); + interfaces.Add(new IPData(IPAddress.Loopback, Network.IPv4RFC5735Loopback, "lo")); } if (bindAddresses.Contains(IPAddress.IPv6Loopback)) { - interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); + interfaces.Add(new IPData(IPAddress.IPv6Loopback, Network.IPv6RFC4291Loopback, "lo")); } } @@ -437,7 +439,7 @@ namespace Jellyfin.Networking.Manager { if (IPAddress.TryParse(ip, out var ipp)) { - remoteAddressFilter.Add(new IPNetwork(ipp, ipp.AddressFamily == AddressFamily.InterNetwork ? 32 : 128)); + remoteAddressFilter.Add(new IPNetwork(ipp, ipp.AddressFamily == AddressFamily.InterNetwork ? Network.MinimumIPv4PrefixSize : Network.MinimumIPv6PrefixSize)); } } @@ -477,8 +479,8 @@ namespace Jellyfin.Networking.Manager } else if (string.Equals(identifier, "external", StringComparison.OrdinalIgnoreCase)) { - publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; - publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement; + publishedServerUrls[new IPData(IPAddress.Any, Network.IPv4Any)] = replacement; + publishedServerUrls[new IPData(IPAddress.IPv6Any, Network.IPv6Any)] = replacement; } else if (string.Equals(identifier, "internal", StringComparison.OrdinalIgnoreCase)) { @@ -656,12 +658,12 @@ namespace Jellyfin.Networking.Manager var loopbackNetworks = new List(); if (IsIPv4Enabled) { - loopbackNetworks.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); + loopbackNetworks.Add(new IPData(IPAddress.Loopback, Network.IPv4RFC5735Loopback, "lo")); } if (IsIPv6Enabled) { - loopbackNetworks.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); + loopbackNetworks.Add(new IPData(IPAddress.IPv6Loopback, Network.IPv6RFC4291Loopback, "lo")); } return loopbackNetworks; @@ -687,11 +689,11 @@ namespace Jellyfin.Networking.Manager if (IsIPv4Enabled && IsIPv6Enabled) { // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any by default - result.Add(new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))); + result.Add(new IPData(IPAddress.IPv6Any, Network.IPv6Any)); } else if (IsIPv4Enabled) { - result.Add(new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))); + result.Add(new IPData(IPAddress.Any, Network.IPv4Any)); } else if (IsIPv6Enabled) { @@ -1047,7 +1049,7 @@ namespace Jellyfin.Networking.Manager } // Fallback to first external interface. - result = NetworkExtensions.FormatIPString(extResult.First().Address); + result = NetworkExtensions.FormatIPString(extResult[0].Address); _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result); return true; } diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index ea3c92011..e1dfa1d31 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -21,9 +21,10 @@ using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Enums; using Jellyfin.Extensions.Json; using Jellyfin.Networking.Configuration; +using Jellyfin.Networking.Constants; +using Jellyfin.Networking.Extensions; using Jellyfin.Server.Configuration; using Jellyfin.Server.Filters; -using MediaBrowser.Common.Net; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Session; using Microsoft.AspNetCore.Authentication; @@ -271,7 +272,7 @@ namespace Jellyfin.Server.Extensions { if (IPAddress.TryParse(allowedProxies[i], out var addr)) { - AddIPAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); + AddIPAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? Network.MinimumIPv4PrefixSize : Network.MinimumIPv6PrefixSize); } else if (NetworkExtensions.TryParseToSubnet(allowedProxies[i], out var subnet)) { @@ -284,7 +285,7 @@ namespace Jellyfin.Server.Extensions { foreach (var address in addresses) { - AddIPAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); + AddIPAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? Network.MinimumIPv4PrefixSize : Network.MinimumIPv6PrefixSize); } } } @@ -292,17 +293,17 @@ namespace Jellyfin.Server.Extensions private static void AddIPAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength) { - if ((!config.EnableIPv4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPv6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) - { - return; - } - if (addr.IsIPv4MappedToIPv6) { addr = addr.MapToIPv4(); } - if (prefixLength == 32) + if ((!config.EnableIPv4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPv6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) + { + return; + } + + if (prefixLength == Network.MinimumIPv4PrefixSize) { options.KnownProxies.Add(addr); } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs deleted file mode 100644 index 47475b3da..000000000 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ /dev/null @@ -1,350 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Text.RegularExpressions; -using Jellyfin.Extensions; -using Microsoft.AspNetCore.HttpOverrides; - -namespace MediaBrowser.Common.Net -{ - /// - /// Defines the . - /// - public static class NetworkExtensions - { - // Use regular expression as CheckHostName isn't RFC5892 compliant. - // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation - private static readonly Regex _fqdnRegex = new Regex(@"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$"); - - /// - /// Returns true if the IPAddress contains an IP6 Local link address. - /// - /// IPAddress object to check. - /// True if it is a local link address. - /// - /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress - /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. - /// - public static bool IsIPv6LinkLocal(IPAddress address) - { - ArgumentNullException.ThrowIfNull(address); - - if (address.IsIPv4MappedToIPv6) - { - address = address.MapToIPv4(); - } - - if (address.AddressFamily != AddressFamily.InterNetworkV6) - { - return false; - } - - // GetAddressBytes - Span octet = stackalloc byte[16]; - address.TryWriteBytes(octet, out _); - uint word = (uint)(octet[0] << 8) + octet[1]; - - return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link. - } - - /// - /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. - /// - /// Subnet mask in CIDR notation. - /// IPv4 or IPv6 family. - /// String value of the subnet mask in dotted decimal notation. - public static IPAddress CidrToMask(byte cidr, AddressFamily family) - { - uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? 32 : 128) - cidr); - addr = ((addr & 0xff000000) >> 24) - | ((addr & 0x00ff0000) >> 8) - | ((addr & 0x0000ff00) << 8) - | ((addr & 0x000000ff) << 24); - return new IPAddress(addr); - } - - /// - /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. - /// - /// Subnet mask in CIDR notation. - /// IPv4 or IPv6 family. - /// String value of the subnet mask in dotted decimal notation. - public static IPAddress CidrToMask(int cidr, AddressFamily family) - { - uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? 32 : 128) - cidr); - addr = ((addr & 0xff000000) >> 24) - | ((addr & 0x00ff0000) >> 8) - | ((addr & 0x0000ff00) << 8) - | ((addr & 0x000000ff) << 24); - return new IPAddress(addr); - } - - /// - /// Convert a subnet mask to a CIDR. IPv4 only. - /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. - /// - /// Subnet mask. - /// Byte CIDR representing the mask. - public static byte MaskToCidr(IPAddress mask) - { - ArgumentNullException.ThrowIfNull(mask); - - byte cidrnet = 0; - if (mask.Equals(IPAddress.Any)) - { - return cidrnet; - } - - // GetAddressBytes - Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; - if (!mask.TryWriteBytes(bytes, out var bytesWritten)) - { - Console.WriteLine("Unable to write address bytes, only {Bytes} bytes written.", bytesWritten); - } - - var zeroed = false; - for (var i = 0; i < bytes.Length; i++) - { - for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1) - { - if (zeroed) - { - // Invalid netmask. - return (byte)~cidrnet; - } - - if ((v & 0x80) == 0) - { - zeroed = true; - } - else - { - cidrnet++; - } - } - } - - return cidrnet; - } - - /// - /// Converts an IPAddress into a string. - /// IPv6 addresses are returned in [ ], with their scope removed. - /// - /// Address to convert. - /// URI safe conversion of the address. - public static string FormatIPString(IPAddress? address) - { - if (address is null) - { - return string.Empty; - } - - var str = address.ToString(); - if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - int i = str.IndexOf('%', StringComparison.Ordinal); - if (i != -1) - { - str = str.Substring(0, i); - } - - return $"[{str}]"; - } - - return str; - } - - /// - /// Try parsing an array of strings into objects, respecting exclusions. - /// Elements without a subnet mask will be represented as with a single IP. - /// - /// Input string array to be parsed. - /// Collection of . - /// Boolean signaling if negated or not negated values should be parsed. - /// True if parsing was successful. - public static bool TryParseToSubnets(string[] values, [NotNullWhen(true)] out IReadOnlyList? result, bool negated = false) - { - if (values is null || values.Length == 0) - { - result = null; - return false; - } - - var tmpResult = new List(); - for (int a = 0; a < values.Length; a++) - { - if (TryParseToSubnet(values[a], out var innerResult, negated)) - { - tmpResult.Add(innerResult); - } - } - - result = tmpResult; - return tmpResult.Count > 0; - } - - /// - /// Try parsing a string into an , respecting exclusions. - /// Inputs without a subnet mask will be represented as with a single IP. - /// - /// Input string to be parsed. - /// An . - /// Boolean signaling if negated or not negated values should be parsed. - /// True if parsing was successful. - public static bool TryParseToSubnet(ReadOnlySpan value, [NotNullWhen(true)] out IPNetwork? result, bool negated = false) - { - var splitString = value.Trim().Split('/'); - if (splitString.MoveNext()) - { - var ipBlock = splitString.Current; - var address = IPAddress.None; - if (negated && ipBlock.StartsWith("!") && IPAddress.TryParse(ipBlock[1..], out var tmpAddress)) - { - address = tmpAddress; - } - else if (!negated && IPAddress.TryParse(ipBlock, out tmpAddress)) - { - address = tmpAddress; - } - - if (address != IPAddress.None) - { - if (splitString.MoveNext()) - { - var subnetBlock = splitString.Current; - if (int.TryParse(subnetBlock, out var netmask)) - { - result = new IPNetwork(address, netmask); - return true; - } - else if (IPAddress.TryParse(subnetBlock, out var netmaskAddress)) - { - result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); - return true; - } - } - else if (address.AddressFamily == AddressFamily.InterNetwork) - { - result = new IPNetwork(address, 32); - return true; - } - else if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - result = new IPNetwork(address, 128); - return true; - } - } - } - - result = null; - return false; - } - - /// - /// Attempts to parse a host span. - /// - /// Host name to parse. - /// Object representing the span, if it has successfully been parsed. - /// true if IPv4 is enabled. - /// true if IPv6 is enabled. - /// true if the parsing is successful, false if not. - public static bool TryParseHost(ReadOnlySpan host, [NotNullWhen(true)] out IPAddress[]? addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) - { - if (host.IsEmpty) - { - addresses = null; - return false; - } - - host = host.Trim(); - - // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. - if (host[0] == '[') - { - int i = host.IndexOf("]", StringComparison.Ordinal); - if (i != -1) - { - return TryParseHost(host[1..(i - 1)], out addresses); - } - - addresses = Array.Empty(); - return false; - } - - var hosts = new List(); - foreach (var splitSpan in host.Split(':')) - { - hosts.Add(splitSpan.ToString()); - } - - if (hosts.Count <= 2) - { - // Is hostname or hostname:port - if (_fqdnRegex.IsMatch(hosts[0])) - { - try - { - addresses = Dns.GetHostAddresses(hosts[0]); - return true; - } - catch (SocketException) - { - // Log and then ignore socket errors, as the result value will just be an empty array. - Console.WriteLine("GetHostAddresses failed."); - } - } - - // Is an IP4 or IP4:port - if (IPAddress.TryParse(hosts[0].AsSpan().LeftPart('/'), out var address)) - { - if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIPv4Enabled && isIPv6Enabled)) - || ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIPv4Enabled && !isIPv6Enabled))) - { - addresses = Array.Empty(); - return false; - } - - addresses = new[] { address }; - - // Host name is an ip4 address, so fake resolve. - return true; - } - } - else if (hosts.Count > 0 && hosts.Count <= 9) // 8 octets + port - { - if (IPAddress.TryParse(host.LeftPart('/'), out var address)) - { - addresses = new[] { address }; - return true; - } - } - - addresses = Array.Empty(); - return false; - } - - /// - /// Gets the broadcast address for a . - /// - /// The . - /// The broadcast address. - public static IPAddress GetBroadcastAddress(IPNetwork network) - { - var addressBytes = network.Prefix.GetAddressBytes(); - if (BitConverter.IsLittleEndian) - { - addressBytes.Reverse(); - } - - uint iPAddress = BitConverter.ToUInt32(addressBytes, 0); - uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0); - uint broadCastIPAddress = iPAddress | ~ipMaskV4; - - return new IPAddress(BitConverter.GetBytes(broadCastIPAddress)); - } - } -} diff --git a/tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs b/tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs index c81fdefe9..2ff7c7de4 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs @@ -1,6 +1,6 @@ using FsCheck; using FsCheck.Xunit; -using MediaBrowser.Common.Net; +using Jellyfin.Networking.Extensions; using Xunit; namespace Jellyfin.Networking.Tests diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 77f18c544..cb8092ae9 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -3,9 +3,9 @@ using System.Collections.Generic; using System.Linq; using System.Net; using Jellyfin.Networking.Configuration; +using Jellyfin.Networking.Extensions; using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.Net; using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging.Abstractions; using Moq;