diff options
Diffstat (limited to 'Jellyfin.Networking')
| -rw-r--r-- | Jellyfin.Networking/Configuration/NetworkConfiguration.cs | 155 | ||||
| -rw-r--r-- | Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs | 2 | ||||
| -rw-r--r-- | Jellyfin.Networking/Constants/Network.cs | 75 | ||||
| -rw-r--r-- | Jellyfin.Networking/Extensions/NetworkExtensions.cs | 344 | ||||
| -rw-r--r-- | Jellyfin.Networking/HappyEyeballs/HttpClientExtension.cs | 120 | ||||
| -rw-r--r-- | Jellyfin.Networking/Manager/NetworkManager.cs | 1548 |
6 files changed, 1226 insertions, 1018 deletions
diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 361dbc814..90ebcd390 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -10,33 +10,18 @@ namespace Jellyfin.Networking.Configuration public class NetworkConfiguration { /// <summary> - /// The default value for <see cref="HttpServerPortNumber"/>. + /// The default value for <see cref="InternalHttpPort"/>. /// </summary> public const int DefaultHttpPort = 8096; /// <summary> - /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsPortNumber"/>. + /// The default value for <see cref="PublicHttpsPort"/> and <see cref="InternalHttpsPort"/>. /// </summary> public const int DefaultHttpsPort = 8920; private string _baseUrl = string.Empty; /// <summary> - /// Gets or sets a value indicating whether the server should force connections over HTTPS. - /// </summary> - public bool RequireHttps { get; set; } - - /// <summary> - /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. - /// </summary> - public string CertificatePath { get; set; } = string.Empty; - - /// <summary> - /// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>. - /// </summary> - public string CertificatePassword { get; set; } = string.Empty; - - /// <summary> /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at. /// </summary> public string BaseUrl @@ -70,24 +55,6 @@ namespace Jellyfin.Networking.Configuration } /// <summary> - /// Gets or sets the public HTTPS port. - /// </summary> - /// <value>The public HTTPS port.</value> - public int PublicHttpsPort { get; set; } = DefaultHttpsPort; - - /// <summary> - /// Gets or sets the HTTP server port number. - /// </summary> - /// <value>The HTTP server port number.</value> - public int HttpServerPortNumber { get; set; } = DefaultHttpPort; - - /// <summary> - /// Gets or sets the HTTPS server port number. - /// </summary> - /// <value>The HTTPS server port number.</value> - public int HttpsPortNumber { get; set; } = DefaultHttpsPort; - - /// <summary> /// Gets or sets a value indicating whether to use HTTPS. /// </summary> /// <remarks> @@ -97,100 +64,104 @@ namespace Jellyfin.Networking.Configuration public bool EnableHttps { get; set; } /// <summary> - /// Gets or sets the public mapped port. + /// Gets or sets a value indicating whether the server should force connections over HTTPS. /// </summary> - /// <value>The public mapped port.</value> - public int PublicPort { get; set; } = DefaultHttpPort; + public bool RequireHttps { get; set; } /// <summary> - /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding. + /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. /// </summary> - public bool UPnPCreateHttpPortMap { get; set; } + public string CertificatePath { get; set; } = string.Empty; /// <summary> - /// Gets or sets the UDPPortRange. + /// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>. /// </summary> - public string UDPPortRange { get; set; } = string.Empty; + public string CertificatePassword { get; set; } = string.Empty; /// <summary> - /// Gets or sets a value indicating whether gets or sets IPV6 capability. + /// Gets or sets the internal HTTP server port. /// </summary> - public bool EnableIPV6 { get; set; } + /// <value>The HTTP server port.</value> + public int InternalHttpPort { get; set; } = DefaultHttpPort; /// <summary> - /// Gets or sets a value indicating whether gets or sets IPV4 capability. + /// Gets or sets the internal HTTPS server port. /// </summary> - public bool EnableIPV4 { get; set; } = true; + /// <value>The HTTPS server port.</value> + public int InternalHttpsPort { get; set; } = DefaultHttpsPort; /// <summary> - /// Gets or sets a value indicating whether detailed SSDP logs are sent to the console/log. - /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to have any effect. + /// Gets or sets the public HTTP port. /// </summary> - public bool EnableSSDPTracing { get; set; } + /// <value>The public HTTP port.</value> + public int PublicHttpPort { get; set; } = DefaultHttpPort; /// <summary> - /// Gets or sets the SSDPTracingFilter - /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log. - /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work. + /// Gets or sets the public HTTPS port. /// </summary> - public string SSDPTracingFilter { get; set; } = string.Empty; + /// <value>The public HTTPS port.</value> + public int PublicHttpsPort { get; set; } = DefaultHttpsPort; /// <summary> - /// Gets or sets the number of times SSDP UDP messages are sent. + /// Gets or sets a value indicating whether Autodiscovery is enabled. /// </summary> - public int UDPSendCount { get; set; } = 2; + public bool AutoDiscovery { get; set; } = true; /// <summary> - /// Gets or sets the delay between each groups of SSDP messages (in ms). + /// Gets or sets a value indicating whether to enable automatic port forwarding. /// </summary> - public int UDPSendDelay { get; set; } = 100; + public bool EnableUPnP { get; set; } /// <summary> - /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding. + /// Gets or sets a value indicating whether IPv6 is enabled. /// </summary> - public bool IgnoreVirtualInterfaces { get; set; } = true; + public bool EnableIPv4 { get; set; } = true; /// <summary> - /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>. + /// Gets or sets a value indicating whether IPv6 is enabled. /// </summary> - public string VirtualInterfaceNames { get; set; } = "vEthernet*"; + public bool EnableIPv6 { get; set; } /// <summary> - /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor. + /// Gets or sets a value indicating whether access from outside of the LAN is permitted. /// </summary> - public int GatewayMonitorPeriod { get; set; } = 60; + public bool EnableRemoteAccess { get; set; } = true; /// <summary> - /// Gets a value indicating whether multi-socket binding is available. + /// Gets or sets the subnets that are deemed to make up the LAN. /// </summary> - public bool EnableMultiSocketBinding { get; } = true; + public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>(); /// <summary> - /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network. - /// Depending on the address range implemented ULA ranges might not be used. + /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used. /// </summary> - public bool TrustAllIP6Interfaces { get; set; } + public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>(); /// <summary> - /// Gets or sets the ports that HDHomerun uses. + /// Gets or sets the known proxies. /// </summary> - public string HDHomerunPortRange { get; set; } = string.Empty; + public string[] KnownProxies { get; set; } = Array.Empty<string>(); /// <summary> - /// Gets or sets the PublishedServerUriBySubnet - /// Gets or sets PublishedServerUri to advertise for specific subnets. + /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be ignored for the purposes of binding. /// </summary> - public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>(); + public bool IgnoreVirtualInterfaces { get; set; } = true; /// <summary> - /// Gets or sets a value indicating whether Autodiscovery tracing is enabled. + /// Gets or sets a value indicating the interface name prefixes that should be ignored. The list can be comma separated and values are case-insensitive. <seealso cref="IgnoreVirtualInterfaces"/>. /// </summary> - public bool AutoDiscoveryTracing { get; set; } + public string[] VirtualInterfaceNames { get; set; } = new string[] { "veth" }; /// <summary> - /// Gets or sets a value indicating whether Autodiscovery is enabled. + /// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests. /// </summary> - public bool AutoDiscovery { get; set; } = true; + public bool EnablePublishedServerUriByRequest { get; set; } = false; + + /// <summary> + /// Gets or sets the PublishedServerUriBySubnet + /// Gets or sets PublishedServerUri to advertise for specific subnets. + /// </summary> + public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>(); /// <summary> /// Gets or sets the filter for remote IP connectivity. Used in conjunction with <seealso cref="IsRemoteIPFilterBlacklist"/>. @@ -201,35 +172,5 @@ namespace Jellyfin.Networking.Configuration /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist. /// </summary> public bool IsRemoteIPFilterBlacklist { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether to enable automatic port forwarding. - /// </summary> - public bool EnableUPnP { get; set; } - - /// <summary> - /// Gets or sets a value indicating whether access outside of the LAN is permitted. - /// </summary> - public bool EnableRemoteAccess { get; set; } = true; - - /// <summary> - /// Gets or sets the subnets that are deemed to make up the LAN. - /// </summary> - public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>(); - - /// <summary> - /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used. - /// </summary> - public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>(); - - /// <summary> - /// Gets or sets the known proxies. If the proxy is a network, it's added to the KnownNetworks. - /// </summary> - public string[] KnownProxies { get; set; } = Array.Empty<string>(); - - /// <summary> - /// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests. - /// </summary> - public bool EnablePublishedServerUriByRequest { get; set; } = false; } } diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs index 8cbe398b0..3ba6bb8fc 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs @@ -14,7 +14,7 @@ namespace Jellyfin.Networking.Configuration /// <returns>The <see cref="NetworkConfiguration"/>.</returns> public static NetworkConfiguration GetNetworkConfiguration(this IConfigurationManager config) { - return config.GetConfiguration<NetworkConfiguration>("network"); + return config.GetConfiguration<NetworkConfiguration>(NetworkConfigurationStore.StoreKey); } } } 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; + +/// <summary> +/// Networking constants. +/// </summary> +public static class Network +{ + /// <summary> + /// IPv4 mask bytes. + /// </summary> + public const int IPv4MaskBytes = 4; + + /// <summary> + /// IPv6 mask bytes. + /// </summary> + public const int IPv6MaskBytes = 16; + + /// <summary> + /// Minimum IPv4 prefix size. + /// </summary> + public const int MinimumIPv4PrefixSize = 32; + + /// <summary> + /// Minimum IPv6 prefix size. + /// </summary> + public const int MinimumIPv6PrefixSize = 128; + + /// <summary> + /// Whole IPv4 address space. + /// </summary> + public static readonly IPNetwork IPv4Any = new IPNetwork(IPAddress.Any, 0); + + /// <summary> + /// Whole IPv6 address space. + /// </summary> + public static readonly IPNetwork IPv6Any = new IPNetwork(IPAddress.IPv6Any, 0); + + /// <summary> + /// IPv4 Loopback as defined in RFC 5735. + /// </summary> + public static readonly IPNetwork IPv4RFC5735Loopback = new IPNetwork(IPAddress.Loopback, 8); + + /// <summary> + /// IPv4 private class A as defined in RFC 1918. + /// </summary> + public static readonly IPNetwork IPv4RFC1918PrivateClassA = new IPNetwork(IPAddress.Parse("10.0.0.0"), 8); + + /// <summary> + /// IPv4 private class B as defined in RFC 1918. + /// </summary> + public static readonly IPNetwork IPv4RFC1918PrivateClassB = new IPNetwork(IPAddress.Parse("172.16.0.0"), 12); + + /// <summary> + /// IPv4 private class C as defined in RFC 1918. + /// </summary> + public static readonly IPNetwork IPv4RFC1918PrivateClassC = new IPNetwork(IPAddress.Parse("192.168.0.0"), 16); + + /// <summary> + /// IPv6 loopback as defined in RFC 4291. + /// </summary> + public static readonly IPNetwork IPv6RFC4291Loopback = new IPNetwork(IPAddress.IPv6Loopback, 128); + + /// <summary> + /// IPv6 site local as defined in RFC 4291. + /// </summary> + public static readonly IPNetwork IPv6RFC4291SiteLocal = new IPNetwork(IPAddress.Parse("fe80::"), 10); + + /// <summary> + /// IPv6 unique local as defined in RFC 4193. + /// </summary> + 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..e45fa3bcb --- /dev/null +++ b/Jellyfin.Networking/Extensions/NetworkExtensions.cs @@ -0,0 +1,344 @@ +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; + +/// <summary> +/// Defines the <see cref="NetworkExtensions" />. +/// </summary> +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(); + + /// <summary> + /// Returns true if the IPAddress contains an IP6 Local link address. + /// </summary> + /// <param name="address">IPAddress object to check.</param> + /// <returns>True if it is a local link address.</returns> + /// <remarks> + /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress + /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. + /// </remarks> + public static bool IsIPv6LinkLocal(IPAddress address) + { + ArgumentNullException.ThrowIfNull(address); + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + if (address.AddressFamily != AddressFamily.InterNetworkV6) + { + return false; + } + + // GetAddressBytes + Span<byte> 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. + } + + /// <summary> + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// </summary> + /// <param name="cidr">Subnet mask in CIDR notation.</param> + /// <param name="family">IPv4 or IPv6 family.</param> + /// <returns>String value of the subnet mask in dotted decimal notation.</returns> + 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); + } + + /// <summary> + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// </summary> + /// <param name="cidr">Subnet mask in CIDR notation.</param> + /// <param name="family">IPv4 or IPv6 family.</param> + /// <returns>String value of the subnet mask in dotted decimal notation.</returns> + 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); + } + + /// <summary> + /// Convert a subnet mask to a CIDR. IPv4 only. + /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. + /// </summary> + /// <param name="mask">Subnet mask.</param> + /// <returns>Byte CIDR representing the mask.</returns> + public static byte MaskToCidr(IPAddress mask) + { + ArgumentNullException.ThrowIfNull(mask); + + byte cidrnet = 0; + if (mask.Equals(IPAddress.Any)) + { + return cidrnet; + } + + // GetAddressBytes + Span<byte> 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; + } + + /// <summary> + /// Converts an IPAddress into a string. + /// IPv6 addresses are returned in [ ], with their scope removed. + /// </summary> + /// <param name="address">Address to convert.</param> + /// <returns>URI safe conversion of the address.</returns> + 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; + } + + /// <summary> + /// Try parsing an array of strings into <see cref="IPNetwork"/> objects, respecting exclusions. + /// Elements without a subnet mask will be represented as <see cref="IPNetwork"/> with a single IP. + /// </summary> + /// <param name="values">Input string array to be parsed.</param> + /// <param name="result">Collection of <see cref="IPNetwork"/>.</param> + /// <param name="negated">Boolean signaling if negated or not negated values should be parsed.</param> + /// <returns><c>True</c> if parsing was successful.</returns> + public static bool TryParseToSubnets(string[] values, [NotNullWhen(true)] out IReadOnlyList<IPNetwork>? result, bool negated = false) + { + if (values is null || values.Length == 0) + { + result = null; + return false; + } + + var tmpResult = new List<IPNetwork>(); + 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; + } + + /// <summary> + /// Try parsing a string into an <see cref="IPNetwork"/>, respecting exclusions. + /// Inputs without a subnet mask will be represented as <see cref="IPNetwork"/> with a single IP. + /// </summary> + /// <param name="value">Input string to be parsed.</param> + /// <param name="result">An <see cref="IPNetwork"/>.</param> + /// <param name="negated">Boolean signaling if negated or not negated values should be parsed.</param> + /// <returns><c>True</c> if parsing was successful.</returns> + public static bool TryParseToSubnet(ReadOnlySpan<char> 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<char>("!") && 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; + } + + /// <summary> + /// Attempts to parse a host span. + /// </summary> + /// <param name="host">Host name to parse.</param> + /// <param name="addresses">Object representing the span, if it has successfully been parsed.</param> + /// <param name="isIPv4Enabled"><c>true</c> if IPv4 is enabled.</param> + /// <param name="isIPv6Enabled"><c>true</c> if IPv6 is enabled.</param> + /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns> + public static bool TryParseHost(ReadOnlySpan<char> host, [NotNullWhen(true)] out IPAddress[]? addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) + { + host = host.Trim(); + if (host.IsEmpty) + { + addresses = null; + return false; + } + + // 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<IPAddress>(); + return false; + } + + var hosts = new List<string>(); + 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) + { + // Ignore socket errors, as the result value will just be an empty array. + } + } + + // 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<IPAddress>(); + 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<IPAddress>(); + return false; + } + + /// <summary> + /// Gets the broadcast address for a <see cref="IPNetwork"/>. + /// </summary> + /// <param name="network">The <see cref="IPNetwork"/>.</param> + /// <returns>The broadcast address.</returns> + public static IPAddress GetBroadcastAddress(IPNetwork network) + { + var addressBytes = network.Prefix.GetAddressBytes(); + 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/HappyEyeballs/HttpClientExtension.cs b/Jellyfin.Networking/HappyEyeballs/HttpClientExtension.cs new file mode 100644 index 000000000..59e6956c7 --- /dev/null +++ b/Jellyfin.Networking/HappyEyeballs/HttpClientExtension.cs @@ -0,0 +1,120 @@ +/* +The MIT License (MIT) + +Copyright (c) .NET Foundation and Contributors + +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. +*/ + +using System.IO; +using System.Net.Http; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; + +namespace Jellyfin.Networking.HappyEyeballs +{ + /// <summary> + /// Defines the <see cref="HttpClientExtension"/> class. + /// + /// Implementation taken from https://github.com/ppy/osu-framework/pull/4191 . + /// </summary> + public static class HttpClientExtension + { + /// <summary> + /// Gets or sets a value indicating whether the client should use IPv6. + /// </summary> + public static bool UseIPv6 { get; set; } = true; + + /// <summary> + /// Implements the httpclient callback method. + /// </summary> + /// <param name="context">The <see cref="SocketsHttpConnectionContext"/> instance.</param> + /// <param name="cancellationToken">The <see cref="CancellationToken"/> instance.</param> + /// <returns>The http steam.</returns> + public static async ValueTask<Stream> OnConnect(SocketsHttpConnectionContext context, CancellationToken cancellationToken) + { + if (!UseIPv6) + { + return await AttemptConnection(AddressFamily.InterNetwork, context, cancellationToken).ConfigureAwait(false); + } + + using var cancelIPv6 = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var tryConnectAsyncIPv6 = AttemptConnection(AddressFamily.InterNetworkV6, context, cancelIPv6.Token); + + // GetAwaiter().GetResult() is used instead of .Result as this results in improved exception handling. + // The tasks have already been completed. + // See https://github.com/dotnet/corefx/pull/29792/files#r189415885 for more details. + if (await Task.WhenAny(tryConnectAsyncIPv6, Task.Delay(200, cancelIPv6.Token)).ConfigureAwait(false) == tryConnectAsyncIPv6 && tryConnectAsyncIPv6.IsCompletedSuccessfully) + { + cancelIPv6.Cancel(); + return tryConnectAsyncIPv6.GetAwaiter().GetResult(); + } + + using var cancelIPv4 = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var tryConnectAsyncIPv4 = AttemptConnection(AddressFamily.InterNetwork, context, cancelIPv4.Token); + + if (await Task.WhenAny(tryConnectAsyncIPv6, tryConnectAsyncIPv4).ConfigureAwait(false) == tryConnectAsyncIPv6) + { + if (tryConnectAsyncIPv6.IsCompletedSuccessfully) + { + cancelIPv4.Cancel(); + return tryConnectAsyncIPv6.GetAwaiter().GetResult(); + } + + return tryConnectAsyncIPv4.GetAwaiter().GetResult(); + } + else + { + if (tryConnectAsyncIPv4.IsCompletedSuccessfully) + { + cancelIPv6.Cancel(); + return tryConnectAsyncIPv4.GetAwaiter().GetResult(); + } + + return tryConnectAsyncIPv6.GetAwaiter().GetResult(); + } + } + + private static async Task<Stream> AttemptConnection(AddressFamily addressFamily, SocketsHttpConnectionContext context, CancellationToken cancellationToken) + { + // The following socket constructor will create a dual-mode socket on systems where IPV6 is available. + var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp) + { + // Turn off Nagle's algorithm since it degrades performance in most HttpClient scenarios. + NoDelay = true + }; + + try + { + await socket.ConnectAsync(context.DnsEndPoint, cancellationToken).ConfigureAwait(false); + // The stream should take the ownership of the underlying socket, + // closing it when it's disposed. + return new NetworkStream(socket, ownsSocket: true); + } + catch + { + socket.Dispose(); + throw; + } + } + } +} diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index a6d5252ff..f20e28526 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1,57 +1,46 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; -using System.Threading.Tasks; +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; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Logging; namespace Jellyfin.Networking.Manager { /// <summary> /// Class to take care of network interface management. - /// Note: The normal collection methods and properties will not work with Collection{IPObject}. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>. /// </summary> public class NetworkManager : INetworkManager, IDisposable { /// <summary> - /// Contains the description of the interface along with its index. - /// </summary> - private readonly Dictionary<string, int> _interfaceNames; - - /// <summary> /// Threading lock for network properties. /// </summary> - private readonly object _intLock = new object(); - - /// <summary> - /// List of all interface addresses and masks. - /// </summary> - private readonly Collection<IPObject> _interfaceAddresses; - - /// <summary> - /// List of all interface MAC addresses. - /// </summary> - private readonly List<PhysicalAddress> _macAddresses; + private readonly object _initLock; private readonly ILogger<NetworkManager> _logger; private readonly IConfigurationManager _configurationManager; - private readonly object _eventFireLock; + private readonly object _networkEventLock; /// <summary> - /// Holds the bind address overrides. + /// Holds the published server URLs and the IPs to use them on. /// </summary> - private readonly Dictionary<IPNetAddress, string> _publishedServerUrls; + private IReadOnlyDictionary<IPData, string> _publishedServerUrls; + + private IReadOnlyList<IPNetwork> _remoteAddressFilter; /// <summary> /// Used to stop "event-racing conditions". @@ -59,35 +48,25 @@ namespace Jellyfin.Networking.Manager private bool _eventfire; /// <summary> - /// Unfiltered user defined LAN subnets. (<see cref="NetworkConfiguration.LocalNetworkSubnets"/>) - /// or internal interface network subnets if undefined by user. - /// </summary> - private Collection<IPObject> _lanSubnets; - - /// <summary> - /// User defined list of subnets to excluded from the LAN. - /// </summary> - private Collection<IPObject> _excludedSubnets; - - /// <summary> - /// List of interface addresses to bind the WS. + /// List of all interface MAC addresses. /// </summary> - private Collection<IPObject> _bindAddresses; + private IReadOnlyList<PhysicalAddress> _macAddresses; /// <summary> - /// List of interface addresses to exclude from bind. + /// Dictionary containing interface addresses and their subnets. /// </summary> - private Collection<IPObject> _bindExclusions; + private IReadOnlyList<IPData> _interfaces; /// <summary> - /// Caches list of all internal filtered interface addresses and masks. + /// Unfiltered user defined LAN subnets (<see cref="NetworkConfiguration.LocalNetworkSubnets"/>) + /// or internal interface network subnets if undefined by user. /// </summary> - private Collection<IPObject> _internalInterfaces; + private IReadOnlyList<IPNetwork> _lanSubnets; /// <summary> - /// Flag set when no custom LAN has been defined in the configuration. + /// User defined list of subnets to excluded from the LAN. /// </summary> - private bool _usingPrivateAddresses; + private IReadOnlyList<IPNetwork> _excludedSubnets; /// <summary> /// True if this object is disposed. @@ -102,14 +81,17 @@ namespace Jellyfin.Networking.Manager #pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in UpdateSettings function. Compiler doesn't yet recognise this. public NetworkManager(IConfigurationManager configurationManager, ILogger<NetworkManager> logger) { - _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager)); + ArgumentNullException.ThrowIfNull(logger); + ArgumentNullException.ThrowIfNull(configurationManager); - _interfaceAddresses = new Collection<IPObject>(); + _logger = logger; + _configurationManager = configurationManager; + _initLock = new(); + _interfaces = new List<IPData>(); _macAddresses = new List<PhysicalAddress>(); - _interfaceNames = new Dictionary<string, int>(); - _publishedServerUrls = new Dictionary<IPNetAddress, string>(); - _eventFireLock = new object(); + _publishedServerUrls = new Dictionary<IPData, string>(); + _networkEventLock = new object(); + _remoteAddressFilter = new List<IPNetwork>(); UpdateSettings(_configurationManager.GetNetworkConfiguration()); @@ -131,46 +113,24 @@ namespace Jellyfin.Networking.Manager public static string MockNetworkSettings { get; set; } = string.Empty; /// <summary> - /// Gets or sets a value indicating whether IP6 is enabled. + /// Gets a value indicating whether IP4 is enabled. /// </summary> - public bool IsIP6Enabled { get; set; } + public bool IsIPv4Enabled => _configurationManager.GetNetworkConfiguration().EnableIPv4; /// <summary> - /// Gets or sets a value indicating whether IP4 is enabled. + /// Gets a value indicating whether IP6 is enabled. /// </summary> - public bool IsIP4Enabled { get; set; } - - /// <inheritdoc/> - public Collection<IPObject> RemoteAddressFilter { get; private set; } + public bool IsIPv6Enabled => _configurationManager.GetNetworkConfiguration().EnableIPv6; /// <summary> /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. /// </summary> - public bool TrustAllIP6Interfaces { get; internal set; } + public bool TrustAllIPv6Interfaces { get; private set; } /// <summary> /// Gets the Published server override list. /// </summary> - public Dictionary<IPNetAddress, string> PublishedServerUrls => _publishedServerUrls; - - /// <summary> - /// Creates a new network collection. - /// </summary> - /// <param name="source">Items to assign the collection, or null.</param> - /// <returns>The collection created.</returns> - public static Collection<IPObject> CreateCollection(IEnumerable<IPObject>? source = null) - { - var result = new Collection<IPObject>(); - if (source is not null) - { - foreach (var item in source) - { - result.AddItem(item, false); - } - } - - return result; - } + public IReadOnlyDictionary<IPData, string> PublishedServerUrls => _publishedServerUrls; /// <inheritdoc/> public void Dispose() @@ -179,407 +139,385 @@ namespace Jellyfin.Networking.Manager GC.SuppressFinalize(this); } - /// <inheritdoc/> - public IReadOnlyCollection<PhysicalAddress> GetMacAddresses() + /// <summary> + /// Handler for network change events. + /// </summary> + /// <param name="sender">Sender.</param> + /// <param name="e">A <see cref="NetworkAvailabilityEventArgs"/> containing network availability information.</param> + private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) { - // Populated in construction - so always has values. - return _macAddresses; + _logger.LogDebug("Network availability changed."); + HandleNetworkChange(); } - /// <inheritdoc/> - public bool IsGatewayInterface(IPObject? addressObj) + /// <summary> + /// Handler for network change events. + /// </summary> + /// <param name="sender">Sender.</param> + /// <param name="e">An <see cref="EventArgs"/>.</param> + private void OnNetworkAddressChanged(object? sender, EventArgs e) { - var address = addressObj?.Address ?? IPAddress.None; - return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0); + _logger.LogDebug("Network address change detected."); + HandleNetworkChange(); } - /// <inheritdoc/> - public bool IsGatewayInterface(IPAddress? addressObj) + /// <summary> + /// Triggers our event, and re-loads interface information. + /// </summary> + private void HandleNetworkChange() { - return _internalInterfaces.Any(i => i.Address.Equals(addressObj ?? IPAddress.None) && i.Tag < 0); + lock (_networkEventLock) + { + if (!_eventfire) + { + _logger.LogDebug("Network Address Change Event."); + // As network events tend to fire one after the other only fire once every second. + _eventfire = true; + OnNetworkChange(); + } + } } - /// <inheritdoc/> - public Collection<IPObject> GetLoopbacks() + /// <summary> + /// Waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. + /// </summary> + private void OnNetworkChange() { - Collection<IPObject> nc = new Collection<IPObject>(); - if (IsIP4Enabled) + try { - nc.AddItem(IPAddress.Loopback); - } + Thread.Sleep(2000); + var networkConfig = _configurationManager.GetNetworkConfiguration(); + if (IsIPv6Enabled && !Socket.OSSupportsIPv6) + { + UpdateSettings(networkConfig); + } + else + { + InitialiseInterfaces(); + InitialiseLan(networkConfig); + EnforceBindSettings(networkConfig); + } - if (IsIP6Enabled) + NetworkChanged?.Invoke(this, EventArgs.Empty); + } + finally { - nc.AddItem(IPAddress.IPv6Loopback); + _eventfire = false; } - - return nc; } - /// <inheritdoc/> - public bool IsExcluded(IPAddress ip) - { - return _excludedSubnets.ContainsAddress(ip); - } - - /// <inheritdoc/> - public bool IsExcluded(EndPoint ip) - { - return ip is not null && IsExcluded(((IPEndPoint)ip).Address); - } - - /// <inheritdoc/> - public Collection<IPObject> CreateIPCollection(string[] values, bool negated = false) + /// <summary> + /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state. + /// Generate a list of all active mac addresses that aren't loopback addresses. + /// </summary> + private void InitialiseInterfaces() { - Collection<IPObject> col = new Collection<IPObject>(); - if (values is null) + lock (_initLock) { - return col; - } + _logger.LogDebug("Refreshing interfaces."); - for (int a = 0; a < values.Length; a++) - { - string v = values[a].Trim(); + var interfaces = new List<IPData>(); + var macAddresses = new List<PhysicalAddress>(); try { - if (v.StartsWith('!')) + var nics = NetworkInterface.GetAllNetworkInterfaces() + .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up); + + foreach (NetworkInterface adapter in nics) { - if (negated) + try { - AddToCollection(col, v[1..]); - } - } - else if (!negated) - { - AddToCollection(col, v); - } - } - catch (ArgumentException e) - { - _logger.LogWarning(e, "Ignoring LAN value {Value}.", v); - } - } + var ipProperties = adapter.GetIPProperties(); + var mac = adapter.GetPhysicalAddress(); - return col; - } + // Populate MAC list + if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && PhysicalAddress.None.Equals(mac)) + { + macAddresses.Add(mac); + } - /// <inheritdoc/> - public Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false) - { - int count = _bindAddresses.Count; + // Populate interface list + foreach (var info in ipProperties.UnicastAddresses) + { + if (IsIPv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) + { + var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); + interfaceObject.Index = ipProperties.GetIPv4Properties().Index; + interfaceObject.Name = adapter.Name; - if (count == 0) - { - if (_bindExclusions.Count > 0) + interfaces.Add(interfaceObject); + } + else if (IsIPv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) + { + var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); + interfaceObject.Index = ipProperties.GetIPv6Properties().Index; + interfaceObject.Name = adapter.Name; + + interfaces.Add(interfaceObject); + } + } + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception ex) +#pragma warning restore CA1031 // Do not catch general exception types + { + // Ignore error, and attempt to continue. + _logger.LogError(ex, "Error encountered parsing interfaces."); + } + } + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception ex) +#pragma warning restore CA1031 // Do not catch general exception types { - // Return all the interfaces except the ones specifically excluded. - return _interfaceAddresses.Exclude(_bindExclusions, false); + _logger.LogError(ex, "Error obtaining interfaces."); } - if (individualInterfaces) + // If no interfaces are found, fallback to loopback interfaces. + if (interfaces.Count == 0) { - return new Collection<IPObject>(_interfaceAddresses); - } + _logger.LogWarning("No interface information available. Using loopback interface(s)."); - // No bind address and no exclusions, so listen on all interfaces. - Collection<IPObject> result = new Collection<IPObject>(); + if (IsIPv4Enabled && !IsIPv6Enabled) + { + interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); + } - if (IsIP6Enabled && IsIP4Enabled) - { - // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any - result.AddItem(IPAddress.IPv6Any); - } - else if (IsIP4Enabled) - { - result.AddItem(IPAddress.Any); - } - else if (IsIP6Enabled) - { - // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses. - foreach (var iface in _interfaceAddresses) + if (!IsIPv4Enabled && IsIPv6Enabled) { - if (iface.AddressFamily == AddressFamily.InterNetworkV6) - { - result.AddItem(iface.Address); - } + interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } } - return result; - } + _logger.LogDebug("Discovered {NumberOfInterfaces} interfaces.", interfaces.Count); + _logger.LogDebug("Interfaces addresses: {Addresses}", interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString())); - // Remove any excluded bind interfaces. - return _bindAddresses.Exclude(_bindExclusions, false); - } - - /// <inheritdoc/> - public string GetBindInterface(string source, out int? port) - { - if (IPHost.TryParse(source, out IPHost host)) - { - return GetBindInterface(host, out port); + _macAddresses = macAddresses; + _interfaces = interfaces; } - - return GetBindInterface(IPHost.None, out port); - } - - /// <inheritdoc/> - public string GetBindInterface(IPAddress source, out int? port) - { - return GetBindInterface(new IPNetAddress(source), out port); } - /// <inheritdoc/> - public string GetBindInterface(HttpRequest source, out int? port) + /// <summary> + /// Initialises internal LAN cache. + /// </summary> + private void InitialiseLan(NetworkConfiguration config) { - string result; - - if (source is not null && IPHost.TryParse(source.Host.Host, out IPHost host)) + lock (_initLock) { - result = GetBindInterface(host, out port); - port ??= source.Host.Port; - } - else - { - result = GetBindInterface(IPNetAddress.None, out port); - port ??= source?.Host.Port; - } - - return result; - } - - /// <inheritdoc/> - public string GetBindInterface(IPObject source, out int? port) - { - port = null; - ArgumentNullException.ThrowIfNull(source); + _logger.LogDebug("Refreshing LAN information."); - // Do we have a source? - bool haveSource = !source.Address.Equals(IPAddress.None); - bool isExternal = false; + // Get configuration options + var subnets = config.LocalNetworkSubnets; - if (haveSource) - { - if (!IsIP6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) + // If no LAN addresses are specified, all private subnets and Loopback are deemed to be the LAN + if (!NetworkExtensions.TryParseToSubnets(subnets, out var lanSubnets, false) || lanSubnets.Count == 0) { - _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); - } + _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); - if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork) - { - _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); - } + var fallbackLanSubnets = new List<IPNetwork>(); + if (IsIPv6Enabled) + { + fallbackLanSubnets.Add(Network.IPv6RFC4291Loopback); // RFC 4291 (Loopback) + fallbackLanSubnets.Add(Network.IPv6RFC4291SiteLocal); // RFC 4291 (Site local) + fallbackLanSubnets.Add(Network.IPv6RFC4193UniqueLocal); // RFC 4193 (Unique local) + } - isExternal = !IsInLocalNetwork(source); + if (IsIPv4Enabled) + { + 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) + } - if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) + _lanSubnets = fallbackLanSubnets; + } + else { - _logger.LogDebug("{Source}: Using BindAddress {Address}:{Port}", source, res, port); - return res; + _lanSubnets = lanSubnets; } - } - _logger.LogDebug("GetBindInterface: Source: {HaveSource}, External: {IsExternal}:", haveSource, isExternal); + _excludedSubnets = NetworkExtensions.TryParseToSubnets(subnets, out var excludedSubnets, true) + ? excludedSubnets + : new List<IPNetwork>(); - // No preference given, so move on to bind addresses. - if (MatchesBindInterface(source, isExternal, out string result)) - { - return result; + _logger.LogInformation("Defined LAN addresses: {0}", _lanSubnets.Select(s => s.Prefix + "/" + s.PrefixLength)); + _logger.LogInformation("Defined LAN exclusions: {0}", _excludedSubnets.Select(s => s.Prefix + "/" + s.PrefixLength)); + _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Where(s => !_excludedSubnets.Contains(s)).Select(s => s.Prefix + "/" + s.PrefixLength)); } + } - if (isExternal && MatchesExternalInterface(source, out result)) - { - return result; - } - - // Get the first LAN interface address that isn't a loopback. - var interfaces = CreateCollection( - _interfaceAddresses - .Exclude(_bindExclusions, false) - .Where(IsInLocalNetwork) - .OrderBy(p => p.Tag)); - - if (interfaces.Count > 0) + /// <summary> + /// Enforce bind addresses and exclusions on available interfaces. + /// </summary> + private void EnforceBindSettings(NetworkConfiguration config) + { + lock (_initLock) { - if (haveSource) + // Respect explicit bind addresses + var interfaces = _interfaces.ToList(); + var localNetworkAddresses = config.LocalNetworkAddresses; + if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses[0])) { - foreach (var intf in interfaces) + var bindAddresses = localNetworkAddresses.Select(p => NetworkExtensions.TryParseToSubnet(p, out var network) + ? network.Prefix + : (interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)) + .Select(x => x.Address) + .FirstOrDefault() ?? IPAddress.None)) + .Where(x => x != IPAddress.None) + .ToHashSet(); + interfaces = interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList(); + + if (bindAddresses.Contains(IPAddress.Loopback)) { - if (intf.Address.Equals(source.Address)) - { - result = FormatIP6String(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface. {Result}", source, result); - return result; - } + interfaces.Add(new IPData(IPAddress.Loopback, Network.IPv4RFC5735Loopback, "lo")); } - // Does the request originate in one of the interface subnets? - // (For systems with multiple internal network cards, and multiple subnets) - foreach (var intf in interfaces) + if (bindAddresses.Contains(IPAddress.IPv6Loopback)) { - if (intf.Contains(source)) - { - result = FormatIP6String(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result); - return result; - } + interfaces.Add(new IPData(IPAddress.IPv6Loopback, Network.IPv6RFC4291Loopback, "lo")); } } - result = FormatIP6String(interfaces.First().Address); - _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result); - return result; - } - - // There isn't any others, so we'll use the loopback. - result = IsIP6Enabled ? "::1" : "127.0.0.1"; - _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result); - return result; - } + // Remove all interfaces matching any virtual machine interface prefix + if (config.IgnoreVirtualInterfaces) + { + // Remove potentially existing * and split config string into prefixes + var virtualInterfacePrefixes = config.VirtualInterfaceNames + .Select(i => i.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase)); - /// <inheritdoc/> - public Collection<IPObject> GetInternalBindAddresses() - { - int count = _bindAddresses.Count; + // Check all interfaces for matches against the prefixes and remove them + if (_interfaces.Count > 0) + { + foreach (var virtualInterfacePrefix in virtualInterfacePrefixes) + { + interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase)); + } + } + } - if (count == 0) - { - if (_bindExclusions.Count > 0) + // Remove all IPv4 interfaces if IPv4 is disabled + if (!IsIPv4Enabled) { - // Return all the internal interfaces except the ones excluded. - return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p))); + interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork); } - // No bind address, so return all internal interfaces. - return CreateCollection(_internalInterfaces); - } - - return new Collection<IPObject>(_bindAddresses.Where(a => IsInLocalNetwork(a)).ToArray()); - } - - /// <inheritdoc/> - public bool IsInLocalNetwork(IPObject address) - { - return IsInLocalNetwork(address.Address); - } - - /// <inheritdoc/> - public bool IsInLocalNetwork(string address) - { - return IPHost.TryParse(address, out IPHost ipHost) && IsInLocalNetwork(ipHost); - } - - /// <inheritdoc/> - public bool IsInLocalNetwork(IPAddress address) - { - ArgumentNullException.ThrowIfNull(address); - - if (address.Equals(IPAddress.None)) - { - return false; - } + // Remove all IPv6 interfaces if IPv6 is disabled + if (!IsIPv6Enabled) + { + interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); + } - // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. - if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) - { - return true; + _logger.LogInformation("Using bind addresses: {0}", interfaces.OrderByDescending(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.Address)); + _interfaces = interfaces; } - - // As private addresses can be redefined by Configuration.LocalNetworkAddresses - return IPAddress.IsLoopback(address) || (_lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address)); } - /// <inheritdoc/> - public bool IsPrivateAddressRange(IPObject address) + /// <summary> + /// Initialises the remote address values. + /// </summary> + private void InitialiseRemote(NetworkConfiguration config) { - ArgumentNullException.ThrowIfNull(address); - - // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. - if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + lock (_initLock) { - return true; - } - - return address.IsPrivateAddressRange(); - } + // Parse config values into filter collection + var remoteIPFilter = config.RemoteIPFilter; + if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First())) + { + // Parse all IPs with netmask to a subnet + var remoteAddressFilter = new List<IPNetwork>(); + var remoteFilteredSubnets = remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(); + if (NetworkExtensions.TryParseToSubnets(remoteFilteredSubnets, out var remoteAddressFilterResult, false)) + { + remoteAddressFilter = remoteAddressFilterResult.ToList(); + } - /// <inheritdoc/> - public bool IsExcludedInterface(IPAddress address) - { - return _bindExclusions.ContainsAddress(address); - } + // Parse everything else as an IP and construct subnet with a single IP + var remoteFilteredIPs = remoteIPFilter.Where(x => !x.Contains('/', StringComparison.OrdinalIgnoreCase)); + foreach (var ip in remoteFilteredIPs) + { + if (IPAddress.TryParse(ip, out var ipp)) + { + remoteAddressFilter.Add(new IPNetwork(ipp, ipp.AddressFamily == AddressFamily.InterNetwork ? Network.MinimumIPv4PrefixSize : Network.MinimumIPv6PrefixSize)); + } + } - /// <inheritdoc/> - public Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null) - { - if (filter is null) - { - return _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks(); + _remoteAddressFilter = remoteAddressFilter; + } } - - return _lanSubnets.Exclude(filter, true); } - /// <inheritdoc/> - public bool IsValidInterfaceAddress(IPAddress address) - { - return _interfaceAddresses.ContainsAddress(address); - } - - /// <inheritdoc/> - public bool TryParseInterface(string token, out Collection<IPObject>? result) + /// <summary> + /// Parses the user defined overrides into the dictionary object. + /// Overrides are the equivalent of localised publishedServerUrl, enabling + /// different addresses to be advertised over different subnets. + /// format is subnet=ipaddress|host|uri + /// when subnet = 0.0.0.0, any external address matches. + /// </summary> + private void InitialiseOverrides(NetworkConfiguration config) { - result = null; - if (string.IsNullOrEmpty(token)) + lock (_initLock) { - return false; - } - - if (_interfaceNames is not null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index)) - { - result = new Collection<IPObject>(); + var publishedServerUrls = new Dictionary<IPData, string>(); + var overrides = config.PublishedServerUriBySubnet; - _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); - - // Replace interface tags with the interface IP's. - foreach (IPNetAddress iface in _interfaceAddresses) + foreach (var entry in overrides) { - if (Math.Abs(iface.Tag) == index - && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) - || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) + var parts = entry.Split('='); + if (parts.Length != 2) + { + _logger.LogError("Unable to parse bind override: {Entry}", entry); + return; + } + + var replacement = parts[1].Trim(); + var identifier = parts[0]; + if (string.Equals(identifier, "all", StringComparison.OrdinalIgnoreCase)) { - result.AddItem(iface, false); + publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement; + } + else if (string.Equals(identifier, "external", StringComparison.OrdinalIgnoreCase)) + { + publishedServerUrls[new IPData(IPAddress.Any, Network.IPv4Any)] = replacement; + publishedServerUrls[new IPData(IPAddress.IPv6Any, Network.IPv6Any)] = replacement; + } + else if (string.Equals(identifier, "internal", StringComparison.OrdinalIgnoreCase)) + { + foreach (var lan in _lanSubnets) + { + var lanPrefix = lan.Prefix; + publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement; + } + } + else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result is not null) + { + var data = new IPData(result.Prefix, result); + publishedServerUrls[data] = replacement; + } + else if (TryParseInterface(identifier, out var ifaces)) + { + foreach (var iface in ifaces) + { + publishedServerUrls[iface] = replacement; + } + } + else + { + _logger.LogError("Unable to parse bind override: {Entry}", entry); } } - return true; + _publishedServerUrls = publishedServerUrls; } - - return false; } - /// <inheritdoc/> - public bool HasRemoteAccess(IPAddress remoteIp) + private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) { - var config = _configurationManager.GetNetworkConfiguration(); - if (config.EnableRemoteAccess) - { - // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. - // If left blank, all remote addresses will be allowed. - if (RemoteAddressFilter.Count > 0 && !IsInLocalNetwork(remoteIp)) - { - // remoteAddressFilter is a whitelist or blacklist. - return RemoteAddressFilter.ContainsAddress(remoteIp) == !config.IsRemoteIPFilterBlacklist; - } - } - else if (!IsInLocalNetwork(remoteIp)) + if (evt.Key.Equals(NetworkConfigurationStore.StoreKey, StringComparison.Ordinal)) { - // Remote not enabled. So everyone should be LAN. - return false; + UpdateSettings((NetworkConfiguration)evt.NewConfiguration); } - - return true; } /// <summary> @@ -588,18 +526,13 @@ namespace Jellyfin.Networking.Manager /// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param> public void UpdateSettings(object configuration) { - NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); + ArgumentNullException.ThrowIfNull(configuration); - IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4; - IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6; + var config = (NetworkConfiguration)configuration; + HappyEyeballs.HttpClientExtension.UseIPv6 = config.EnableIPv6; - if (!IsIP6Enabled && !IsIP4Enabled) - { - _logger.LogError("IPv4 and IPv6 cannot both be disabled."); - IsIP4Enabled = true; - } - - TrustAllIP6Interfaces = config.TrustAllIP6Interfaces; + InitialiseLan(config); + InitialiseRemote(config); if (string.IsNullOrEmpty(MockNetworkSettings)) { @@ -609,20 +542,31 @@ namespace Jellyfin.Networking.Manager { // Format is <IPAddress>,<Index>,<Name>: <next interface>. Set index to -ve to simulate a gateway. var interfaceList = MockNetworkSettings.Split('|'); + var interfaces = new List<IPData>(); foreach (var details in interfaceList) { var parts = details.Split(','); - var address = IPNetAddress.Parse(parts[0]); - var index = int.Parse(parts[1], CultureInfo.InvariantCulture); - address.Tag = index; - _interfaceAddresses.AddItem(address, false); - _interfaceNames[parts[2]] = Math.Abs(index); + if (NetworkExtensions.TryParseToSubnet(parts[0], out var subnet)) + { + var address = subnet.Prefix; + var index = int.Parse(parts[1], CultureInfo.InvariantCulture); + if (address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6) + { + var data = new IPData(address, subnet, parts[2]); + data.Index = index; + interfaces.Add(data); + } + } + else + { + _logger.LogWarning("Could not parse mock interface settings: {Part}", details); + } } + + _interfaces = interfaces; } - InitialiseLAN(config); - InitialiseBind(config); - InitialiseRemote(config); + EnforceBindSettings(config); InitialiseOverrides(config); } @@ -645,548 +589,341 @@ namespace Jellyfin.Networking.Manager } } - /// <summary> - /// Tries to identify the string and return an object of that class. - /// </summary> - /// <param name="addr">String to parse.</param> - /// <param name="result">IPObject to return.</param> - /// <returns><c>true</c> if the value parsed successfully, <c>false</c> otherwise.</returns> - private static bool TryParse(string addr, out IPObject result) + /// <inheritdoc/> + public bool TryParseInterface(string intf, [NotNullWhen(true)] out IReadOnlyList<IPData>? result) { - if (!string.IsNullOrEmpty(addr)) + if (string.IsNullOrEmpty(intf) + || _interfaces is null + || _interfaces.Count == 0) { - // Is it an IP address - if (IPNetAddress.TryParse(addr, out IPNetAddress nw)) - { - result = nw; - return true; - } - - if (IPHost.TryParse(addr, out IPHost h)) - { - result = h; - return true; - } + result = null; + return false; } - result = IPNetAddress.None; - return false; + // Match all interfaces starting with names starting with token + result = _interfaces + .Where(i => i.Name.Equals(intf, StringComparison.OrdinalIgnoreCase) + && ((IsIPv4Enabled && i.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIPv6Enabled && i.Address.AddressFamily == AddressFamily.InterNetworkV6))) + .OrderBy(x => x.Index) + .ToArray(); + return result.Count > 0; } - /// <summary> - /// Converts an IPAddress into a string. - /// Ipv6 addresses are returned in [ ], with their scope removed. - /// </summary> - /// <param name="address">Address to convert.</param> - /// <returns>URI safe conversion of the address.</returns> - private static string FormatIP6String(IPAddress address) + /// <inheritdoc/> + public bool HasRemoteAccess(IPAddress remoteIP) { - var str = address.ToString(); - if (address.AddressFamily == AddressFamily.InterNetworkV6) + var config = _configurationManager.GetNetworkConfiguration(); + if (config.EnableRemoteAccess) { - int i = str.IndexOf("%", StringComparison.OrdinalIgnoreCase); - if (i != -1) + // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely. + // If left blank, all remote addresses will be allowed. + if (_remoteAddressFilter.Any() && !_lanSubnets.Any(x => x.Contains(remoteIP))) { - str = str.Substring(0, i); - } + // remoteAddressFilter is a whitelist or blacklist. + var matches = _remoteAddressFilter.Count(remoteNetwork => remoteNetwork.Contains(remoteIP)); + if ((!config.IsRemoteIPFilterBlacklist && matches > 0) + || (config.IsRemoteIPFilterBlacklist && matches == 0)) + { + return true; + } - return $"[{str}]"; + return false; + } + } + else if (!_lanSubnets.Any(x => x.Contains(remoteIP))) + { + // Remote not enabled. So everyone should be LAN. + return false; } - return str; + return true; } - private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) + /// <inheritdoc/> + public IReadOnlyList<PhysicalAddress> GetMacAddresses() { - if (evt.Key.Equals(NetworkConfigurationStore.StoreKey, StringComparison.Ordinal)) - { - UpdateSettings((NetworkConfiguration)evt.NewConfiguration); - } + // Populated in construction - so always has values. + return _macAddresses; } - /// <summary> - /// Checks the string to see if it matches any interface names. - /// </summary> - /// <param name="token">String to check.</param> - /// <param name="index">Interface index numbers that match.</param> - /// <returns><c>true</c> if an interface name matches the token, <c>False</c> otherwise.</returns> - private bool TryGetInterfaces(string token, [NotNullWhen(true)] out List<int>? index) + /// <inheritdoc/> + public IReadOnlyList<IPData> GetLoopbacks() { - index = null; + if (!IsIPv4Enabled && !IsIPv6Enabled) + { + return Array.Empty<IPData>(); + } - // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. - // Null check required here for automated testing. - if (_interfaceNames is not null && token.Length > 1) + var loopbackNetworks = new List<IPData>(); + if (IsIPv4Enabled) { - bool partial = token[^1] == '*'; - if (partial) - { - token = token[..^1]; - } + loopbackNetworks.Add(new IPData(IPAddress.Loopback, Network.IPv4RFC5735Loopback, "lo")); + } - foreach ((string interfc, int interfcIndex) in _interfaceNames) - { - if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) - || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) - { - index ??= new List<int>(); - index.Add(interfcIndex); - } - } + if (IsIPv6Enabled) + { + loopbackNetworks.Add(new IPData(IPAddress.IPv6Loopback, Network.IPv6RFC4291Loopback, "lo")); } - return index is not null; + return loopbackNetworks; } - /// <summary> - /// Parses a string and adds it into the collection, replacing any interface references. - /// </summary> - /// <param name="col"><see cref="Collection{IPObject}"/>Collection.</param> - /// <param name="token">String value to parse.</param> - private void AddToCollection(Collection<IPObject> col, string token) + /// <inheritdoc/> + public IReadOnlyList<IPData> GetAllBindInterfaces(bool individualInterfaces = false) { - // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. - // Null check required here for automated testing. - if (TryGetInterfaces(token, out var indices)) + if (_interfaces.Count != 0) { - _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); + return _interfaces; + } - // Replace all the interface tags with the interface IP's. - foreach (IPNetAddress iface in _interfaceAddresses) - { - if (indices.Contains(Math.Abs(iface.Tag)) - && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) - || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) - { - col.AddItem(iface); - } - } + // No bind address and no exclusions, so listen on all interfaces. + var result = new List<IPData>(); + + if (individualInterfaces) + { + result.AddRange(_interfaces); + return result; } - else if (TryParse(token, out IPObject obj)) + + if (IsIPv4Enabled && IsIPv6Enabled) { - // Expand if the ip address is "any". - if ((obj.Address.Equals(IPAddress.Any) && IsIP4Enabled) - || (obj.Address.Equals(IPAddress.IPv6Any) && IsIP6Enabled)) - { - foreach (IPNetAddress iface in _interfaceAddresses) - { - if (obj.AddressFamily == iface.AddressFamily) - { - col.AddItem(iface); - } - } - } - else if (!IsIP6Enabled) - { - // Remove IP6 addresses from multi-homed IPHosts. - obj.Remove(AddressFamily.InterNetworkV6); - if (!obj.IsIP6()) - { - col.AddItem(obj); - } - } - else if (!IsIP4Enabled) + // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any by default + result.Add(new IPData(IPAddress.IPv6Any, Network.IPv6Any)); + } + else if (IsIPv4Enabled) + { + result.Add(new IPData(IPAddress.Any, Network.IPv4Any)); + } + else if (IsIPv6Enabled) + { + // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too. + foreach (var iface in _interfaces) { - // Remove IP4 addresses from multi-homed IPHosts. - obj.Remove(AddressFamily.InterNetwork); - if (obj.IsIP6()) + if (iface.AddressFamily == AddressFamily.InterNetworkV6) { - col.AddItem(obj); + result.Add(iface); } } - else - { - col.AddItem(obj); - } - } - else - { - _logger.LogDebug("Invalid or unknown object {Token}.", token); } - } - /// <summary> - /// Handler for network change events. - /// </summary> - /// <param name="sender">Sender.</param> - /// <param name="e">A <see cref="NetworkAvailabilityEventArgs"/> containing network availability information.</param> - private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) - { - _logger.LogDebug("Network availability changed."); - OnNetworkChanged(); + return result; } - /// <summary> - /// Handler for network change events. - /// </summary> - /// <param name="sender">Sender.</param> - /// <param name="e">An <see cref="EventArgs"/>.</param> - private void OnNetworkAddressChanged(object? sender, EventArgs e) + /// <inheritdoc/> + public string GetBindAddress(string source, out int? port) { - _logger.LogDebug("Network address change detected."); - OnNetworkChanged(); + if (!NetworkExtensions.TryParseHost(source, out var addresses, IsIPv4Enabled, IsIPv6Enabled)) + { + addresses = Array.Empty<IPAddress>(); + } + + var result = GetBindAddress(addresses.FirstOrDefault(), out port); + return result; } - /// <summary> - /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. - /// </summary> - /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> - private async Task OnNetworkChangeAsync() + /// <inheritdoc/> + public string GetBindAddress(HttpRequest source, out int? port) { - try - { - await Task.Delay(2000).ConfigureAwait(false); - InitialiseInterfaces(); - // Recalculate LAN caches. - InitialiseLAN(_configurationManager.GetNetworkConfiguration()); + var result = GetBindAddress(source.Host.Host, out port); + port ??= source.Host.Port; - NetworkChanged?.Invoke(this, EventArgs.Empty); - } - finally - { - _eventfire = false; - } + return result; } - /// <summary> - /// Triggers our event, and re-loads interface information. - /// </summary> - private void OnNetworkChanged() + /// <inheritdoc/> + public string GetBindAddress(IPAddress? source, out int? port, bool skipOverrides = false) { - lock (_eventFireLock) + port = null; + + string result; + + if (source is not null) { - if (!_eventfire) + if (IsIPv4Enabled && !IsIPv6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) { - _logger.LogDebug("Network Address Change Event."); - // As network events tend to fire one after the other only fire once every second. - _eventfire = true; - OnNetworkChangeAsync().GetAwaiter().GetResult(); + _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); } - } - } - /// <summary> - /// Parses the user defined overrides into the dictionary object. - /// Overrides are the equivalent of localised publishedServerUrl, enabling - /// different addresses to be advertised over different subnets. - /// format is subnet=ipaddress|host|uri - /// when subnet = 0.0.0.0, any external address matches. - /// </summary> - private void InitialiseOverrides(NetworkConfiguration config) - { - lock (_intLock) - { - _publishedServerUrls.Clear(); - string[] overrides = config.PublishedServerUriBySubnet; - if (overrides is null) + if (!IsIPv4Enabled && IsIPv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) { - return; + _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); } - foreach (var entry in overrides) + bool isExternal = !_lanSubnets.Any(network => network.Contains(source)); + _logger.LogDebug("Trying to get bind address for source {Source} - External: {IsExternal}", source, isExternal); + + if (!skipOverrides && MatchesPublishedServerUrl(source, isExternal, out result)) { - var parts = entry.Split('='); - if (parts.Length != 2) - { - _logger.LogError("Unable to parse bind override: {Entry}", entry); - } - else - { - var replacement = parts[1].Trim(); - if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase)) - { - _publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement; - } - else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase)) - { - _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement; - } - else if (TryParseInterface(parts[0], out Collection<IPObject>? addresses) && addresses is not null) - { - foreach (IPNetAddress na in addresses) - { - _publishedServerUrls[na] = replacement; - } - } - else if (IPNetAddress.TryParse(parts[0], out IPNetAddress result)) - { - _publishedServerUrls[result] = replacement; - } - else - { - _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]); - } - } + return result; } - } - } - - /// <summary> - /// Initialises the network bind addresses. - /// </summary> - private void InitialiseBind(NetworkConfiguration config) - { - lock (_intLock) - { - string[] lanAddresses = config.LocalNetworkAddresses; - // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded. - if (config.IgnoreVirtualInterfaces) + // No preference given, so move on to bind addresses. + if (MatchesBindInterface(source, isExternal, out result)) { - // each virtual interface name must be prepended with the exclusion symbol ! - var virtualInterfaceNames = config.VirtualInterfaceNames.Split(',').Select(p => "!" + p).ToArray(); - if (lanAddresses.Length > 0) - { - var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length]; - Array.Copy(lanAddresses, newList, lanAddresses.Length); - Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length); - lanAddresses = newList; - } - else - { - lanAddresses = virtualInterfaceNames; - } + return result; } - // Read and parse bind addresses and exclusions, removing ones that don't exist. - _bindAddresses = CreateIPCollection(lanAddresses).ThatAreContainedInNetworks(_interfaceAddresses); - _bindExclusions = CreateIPCollection(lanAddresses, true).ThatAreContainedInNetworks(_interfaceAddresses); - _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString()); - _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString()); + if (isExternal && MatchesExternalInterface(source, out result)) + { + return result; + } } - } - /// <summary> - /// Initialises the remote address values. - /// </summary> - private void InitialiseRemote(NetworkConfiguration config) - { - lock (_intLock) + // Get the first LAN interface address that's not excluded and not a loopback address. + // Get all available interfaces, prefer local interfaces + var availableInterfaces = _interfaces.Where(x => !IPAddress.IsLoopback(x.Address)) + .OrderByDescending(x => IsInLocalNetwork(x.Address)) + .ThenBy(x => x.Index) + .ToList(); + + if (availableInterfaces.Count == 0) { - RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter); + // There isn't any others, so we'll use the loopback. + result = IsIPv4Enabled && !IsIPv6Enabled ? "127.0.0.1" : "::1"; + _logger.LogWarning("{Source}: Only loopback {Result} returned, using that as bind address.", source, result); + return result; } - } - /// <summary> - /// Initialises internal LAN cache settings. - /// </summary> - private void InitialiseLAN(NetworkConfiguration config) - { - lock (_intLock) + // If no source address is given, use the preferred (first) interface + if (source is null) { - _logger.LogDebug("Refreshing LAN information."); + result = NetworkExtensions.FormatIPString(availableInterfaces.First().Address); + _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result); + return result; + } - // Get configuration options. - string[] subnets = config.LocalNetworkSubnets; + // Does the request originate in one of the interface subnets? + // (For systems with multiple internal network cards, and multiple subnets) + foreach (var intf in availableInterfaces) + { + if (intf.Subnet.Contains(source)) + { + result = NetworkExtensions.FormatIPString(intf.Address); + _logger.LogDebug("{Source}: Found interface with matching subnet, using it as bind address: {Result}", source, result); + return result; + } + } - // Create lists from user settings. + // Fallback to first available interface + result = NetworkExtensions.FormatIPString(availableInterfaces[0].Address); + _logger.LogDebug("{Source}: No matching interfaces found, using preferred interface as bind address: {Result}", source, result); + return result; + } - _lanSubnets = CreateIPCollection(subnets); - _excludedSubnets = CreateIPCollection(subnets, true).AsNetworks(); + /// <inheritdoc/> + public IReadOnlyList<IPData> GetInternalBindAddresses() + { + // Select all local bind addresses + return _interfaces.Where(x => IsInLocalNetwork(x.Address)) + .OrderBy(x => x.Index) + .ToList(); + } - // If no LAN addresses are specified - all private subnets are deemed to be the LAN - _usingPrivateAddresses = _lanSubnets.Count == 0; + /// <inheritdoc/> + public bool IsInLocalNetwork(string address) + { + if (NetworkExtensions.TryParseToSubnet(address, out var subnet)) + { + return IPAddress.IsLoopback(subnet.Prefix) || (_lanSubnets.Any(x => x.Contains(subnet.Prefix)) && !_excludedSubnets.Any(x => x.Contains(subnet.Prefix))); + } - // NOTE: The order of the commands generating the collection in this statement matters. - // Altering the order will cause the collections to be created incorrectly. - if (_usingPrivateAddresses) + if (NetworkExtensions.TryParseHost(address, out var addresses, IsIPv4Enabled, IsIPv6Enabled)) + { + foreach (var ept in addresses) { - _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); - // Internal interfaces must be private and not excluded. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i))); - - // Subnets are the same as the calculated internal interface. - _lanSubnets = new Collection<IPObject>(); - - if (IsIP6Enabled) + if (IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept)))) { - _lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA - _lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local - } - - if (IsIP4Enabled) - { - _lanSubnets.AddItem(IPNetAddress.Parse("10.0.0.0/8")); - _lanSubnets.AddItem(IPNetAddress.Parse("172.16.0.0/12")); - _lanSubnets.AddItem(IPNetAddress.Parse("192.168.0.0/16")); + return true; } } - else - { - // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(IsInLocalNetwork)); - } - - _logger.LogInformation("Defined LAN addresses: {0}", _lanSubnets.AsString()); - _logger.LogInformation("Defined LAN exclusions: {0}", _excludedSubnets.AsString()); - _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks().AsString()); } + + return false; } - /// <summary> - /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state. - /// Generate a list of all active mac addresses that aren't loopback addresses. - /// </summary> - private void InitialiseInterfaces() + /// <inheritdoc/> + public bool IsInLocalNetwork(IPAddress address) { - lock (_intLock) + ArgumentNullException.ThrowIfNull(address); + + // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. + if ((TrustAllIPv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + || address.Equals(IPAddress.Loopback) + || address.Equals(IPAddress.IPv6Loopback)) { - _logger.LogDebug("Refreshing interfaces."); + return true; + } - _interfaceNames.Clear(); - _interfaceAddresses.Clear(); - _macAddresses.Clear(); + // As private addresses can be redefined by Configuration.LocalNetworkAddresses + return CheckIfLanAndNotExcluded(address); + } - try + private bool CheckIfLanAndNotExcluded(IPAddress address) + { + foreach (var lanSubnet in _lanSubnets) + { + if (lanSubnet.Contains(address)) { - IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces() - .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up); - - foreach (NetworkInterface adapter in nics) + foreach (var excludedSubnet in _excludedSubnets) { - try - { - IPInterfaceProperties ipProperties = adapter.GetIPProperties(); - PhysicalAddress mac = adapter.GetPhysicalAddress(); - - // populate mac list - if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac is not null && mac != PhysicalAddress.None) - { - _macAddresses.Add(mac); - } - - // populate interface address list - foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses) - { - if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) - { - IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask)) - { - // Keep the number of gateways on this interface, along with its index. - Tag = ipProperties.GetIPv4Properties().Index - }; - - int tag = nw.Tag; - if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) - { - // -ve Tags signify the interface has a gateway. - nw.Tag *= -1; - } - - _interfaceAddresses.AddItem(nw, false); - - // Store interface name so we can use the name in Collections. - _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; - _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; - } - else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) - { - IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength) - { - // Keep the number of gateways on this interface, along with its index. - Tag = ipProperties.GetIPv6Properties().Index - }; - - int tag = nw.Tag; - if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) - { - // -ve Tags signify the interface has a gateway. - nw.Tag *= -1; - } - - _interfaceAddresses.AddItem(nw, false); - - // Store interface name so we can use the name in Collections. - _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; - _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; - } - } - } -#pragma warning disable CA1031 // Do not catch general exception types - catch (Exception ex) + if (excludedSubnet.Contains(address)) { - // Ignore error, and attempt to continue. - _logger.LogError(ex, "Error encountered parsing interfaces."); + return false; } -#pragma warning restore CA1031 // Do not catch general exception types - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error in InitialiseInterfaces."); - } - - // If for some reason we don't have an interface info, resolve our DNS name. - if (_interfaceAddresses.Count == 0) - { - _logger.LogError("No interfaces information available. Resolving DNS name."); - IPHost host = new IPHost(Dns.GetHostName()); - foreach (var a in host.GetAddresses()) - { - _interfaceAddresses.AddItem(a); } - if (_interfaceAddresses.Count == 0) - { - _logger.LogWarning("No interfaces information available. Using loopback."); - } - } - - if (IsIP4Enabled) - { - _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback); - } - - if (IsIP6Enabled) - { - _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback); + return true; } - - _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count); - _logger.LogDebug("Interfaces addresses: {0}", _interfaceAddresses.AsString()); } + + return false; } /// <summary> - /// Attempts to match the source against a user defined bind interface. + /// Attempts to match the source against the published server URL overrides. /// </summary> /// <param name="source">IP source address to use.</param> - /// <param name="isInExternalSubnet">True if the source is in the external subnet.</param> - /// <param name="bindPreference">The published server url that matches the source address.</param> - /// <param name="port">The resultant port, if one exists.</param> + /// <param name="isInExternalSubnet">True if the source is in an external subnet.</param> + /// <param name="bindPreference">The published server URL that matches the source address.</param> /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> - private bool MatchesPublishedServerUrl(IPObject source, bool isInExternalSubnet, out string bindPreference, out int? port) + private bool MatchesPublishedServerUrl(IPAddress source, bool isInExternalSubnet, out string bindPreference) { bindPreference = string.Empty; - port = null; + int? port = null; + + var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any) + || x.Key.Address.Equals(IPAddress.IPv6Any) + || x.Key.Subnet.Contains(source)) + .DistinctBy(x => x.Key) + .OrderBy(x => x.Key.Address.Equals(IPAddress.Any) + || x.Key.Address.Equals(IPAddress.IPv6Any)) + .ToList(); // Check for user override. - foreach (var addr in _publishedServerUrls) + foreach (var data in validPublishedServerUrls) { - // Remaining. Match anything. - if (addr.Key.Address.Equals(IPAddress.Broadcast)) - { - bindPreference = addr.Value; - break; - } - - if ((addr.Key.Address.Equals(IPAddress.Any) || addr.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet) + if (isInExternalSubnet && (data.Key.Address.Equals(IPAddress.Any) || data.Key.Address.Equals(IPAddress.IPv6Any))) { // External. - bindPreference = addr.Value; + bindPreference = data.Value; break; } - if (addr.Key.Contains(source)) + // Get address interface. + var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(x => data.Key.Subnet.Contains(x.Address)); + + if (intf?.Address is not null) { - // Match ip address. - bindPreference = addr.Value; + // Match IP address. + bindPreference = data.Value; break; } } if (string.IsNullOrEmpty(bindPreference)) { + _logger.LogDebug("{Source}: No matching bind address override found", source); return false; } @@ -1201,129 +938,120 @@ namespace Jellyfin.Networking.Manager } } + if (port is not null) + { + _logger.LogDebug("{Source}: Matching bind address override found: {Address}:{Port}", source, bindPreference, port); + } + else + { + _logger.LogDebug("{Source}: Matching bind address override found: {Address}", source, bindPreference); + } + return true; } /// <summary> - /// Attempts to match the source against a user defined bind interface. + /// Attempts to match the source against the user defined bind interfaces. /// </summary> /// <param name="source">IP source address to use.</param> /// <param name="isInExternalSubnet">True if the source is in the external subnet.</param> /// <param name="result">The result, if a match is found.</param> /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> - private bool MatchesBindInterface(IPObject source, bool isInExternalSubnet, out string result) + private bool MatchesBindInterface(IPAddress source, bool isInExternalSubnet, out string result) { result = string.Empty; - var addresses = _bindAddresses.Exclude(_bindExclusions, false); - int count = addresses.Count; - if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any))) + int count = _interfaces.Count; + if (count == 1 && (_interfaces[0].Equals(IPAddress.Any) || _interfaces[0].Equals(IPAddress.IPv6Any))) { // Ignore IPAny addresses. count = 0; } - if (count != 0) + if (count == 0) { - // Check to see if any of the bind interfaces are in the same subnet. - - IPAddress? defaultGateway = null; - IPAddress? bindAddress = null; - - if (isInExternalSubnet) - { - // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first. - foreach (var addr in addresses.OrderBy(p => p.Tag)) - { - if (defaultGateway is null && !IsInLocalNetwork(addr)) - { - defaultGateway = addr.Address; - } - - if (bindAddress is null && addr.Contains(source)) - { - bindAddress = addr.Address; - } - - if (defaultGateway is not null && bindAddress is not null) - { - break; - } - } - } - else - { - // Look for the best internal address. - bindAddress = addresses - .Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None))) - .MinBy(p => p.Tag)?.Address; - } - - if (bindAddress is not null) - { - result = FormatIP6String(bindAddress); - _logger.LogDebug("{Source}: GetBindInterface: Has source, found a match bind interface subnets. {Result}", source, result); - return true; - } + return false; + } - if (isInExternalSubnet && defaultGateway is not null) + IPAddress? bindAddress = null; + if (isInExternalSubnet) + { + var externalInterfaces = _interfaces.Where(x => !IsInLocalNetwork(x.Address)) + .OrderBy(x => x.Index) + .ToList(); + if (externalInterfaces.Count > 0) { - result = FormatIP6String(defaultGateway); - _logger.LogDebug("{Source}: GetBindInterface: Using first user defined external interface. {Result}", source, result); + // Check to see if any of the external bind interfaces are in the same subnet as the source. + // If none exists, this will select the first external interface if there is one. + bindAddress = externalInterfaces + .OrderByDescending(x => x.Subnet.Contains(source)) + .ThenBy(x => x.Index) + .Select(x => x.Address) + .First(); + + result = NetworkExtensions.FormatIPString(bindAddress); + _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result); return true; } - result = FormatIP6String(addresses[0].Address); - _logger.LogDebug("{Source}: GetBindInterface: Selected first user defined interface. {Result}", source, result); + _logger.LogWarning("{Source}: External request received, no matching external bind address found, trying internal addresses.", source); + } + else + { + // Check to see if any of the internal bind interfaces are in the same subnet as the source. + // If none exists, this will select the first internal interface if there is one. + bindAddress = _interfaces.Where(x => IsInLocalNetwork(x.Address)) + .OrderByDescending(x => x.Subnet.Contains(source)) + .ThenBy(x => x.Index) + .Select(x => x.Address) + .FirstOrDefault(); - if (isInExternalSubnet) + if (bindAddress is not null) { - _logger.LogWarning("{Source}: External request received, however, only an internal interface bind found.", source); + result = NetworkExtensions.FormatIPString(bindAddress); + _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result); + return true; } - - return true; } return false; } /// <summary> - /// Attempts to match the source against an external interface. + /// Attempts to match the source against external interfaces. /// </summary> /// <param name="source">IP source address to use.</param> /// <param name="result">The result, if a match is found.</param> /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> - private bool MatchesExternalInterface(IPObject source, out string result) + private bool MatchesExternalInterface(IPAddress source, out string result) { - result = string.Empty; - // Get the first WAN interface address that isn't a loopback. - var extResult = _interfaceAddresses - .Exclude(_bindExclusions, false) - .Where(p => !IsInLocalNetwork(p)) - .OrderBy(p => p.Tag) - .ToList(); + // Get the first external interface address that isn't a loopback. + var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address)).OrderBy(x => x.Index).ToArray(); - if (extResult.Any()) + // No external interface found + if (extResult.Length == 0) { - // Does the request originate in one of the interface subnets? - // (For systems with multiple internal network cards, and multiple subnets) - foreach (var intf in extResult) + result = string.Empty; + _logger.LogWarning("{Source}: External request received, but no external interface found. Need to route through internal network.", source); + return false; + } + + // Does the request originate in one of the interface subnets? + // (For systems with multiple network cards and/or multiple subnets) + foreach (var intf in extResult) + { + if (intf.Subnet.Contains(source)) { - if (!IsInLocalNetwork(intf) && intf.Contains(source)) - { - result = FormatIP6String(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range. {Result}", source, result); - return true; - } + result = NetworkExtensions.FormatIPString(intf.Address); + _logger.LogDebug("{Source}: Found external interface with matching subnet, using it as bind address: {Result}", source, result); + return true; } - - result = FormatIP6String(extResult.First().Address); - _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface. {Result}", source, result); - return true; } - _logger.LogDebug("{Source}: External request received, but no WAN interface found. Need to route through internal network.", source); - return false; + // Fallback to first external interface. + result = NetworkExtensions.FormatIPString(extResult[0].Address); + _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result); + return true; } } } |
