From 066db8ac7fcece0ab3420b6b6c03e420d22c7306 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Tue, 19 Jul 2022 21:28:04 +0200 Subject: Migrate NetworkManager and Tests to native .NET IP objects --- MediaBrowser.Common/Net/NetworkExtensions.cs | 309 ++++++++++++--------------- 1 file changed, 135 insertions(+), 174 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 264bfacb4..55ec322f4 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,6 +1,9 @@ using System; -using System.Collections.ObjectModel; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Net; +using System.Net.Sockets; +using System.Text.RegularExpressions; namespace MediaBrowser.Common.Net { @@ -10,251 +13,209 @@ namespace MediaBrowser.Common.Net public static class NetworkExtensions { /// - /// Add an address to the collection. + /// Returns true if the IPAddress contains an IP6 Local link address. /// - /// The . - /// Item to add. - public static void AddItem(this Collection source, IPAddress ip) + /// IPAddress object to check. + /// True if it is a local link address. + /// + /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress + /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. + /// + public static bool IsIPv6LinkLocal(IPAddress address) { - if (!source.ContainsAddress(ip)) + if (address == null) { - source.Add(new IPNetAddress(ip, 32)); + throw new ArgumentNullException(nameof(address)); } - } - /// - /// Adds a network to the collection. - /// - /// The . - /// Item to add. - /// If true the values are treated as subnets. - /// If false items are addresses. - public static void AddItem(this Collection source, IPObject item, bool itemsAreNetworks = true) - { - if (!source.ContainsAddress(item) || !itemsAreNetworks) + if (address.IsIPv4MappedToIPv6) { - source.Add(item); + address = address.MapToIPv4(); } - } - /// - /// Converts this object to a string. - /// - /// The . - /// Returns a string representation of this object. - public static string AsString(this Collection source) - { - return $"[{string.Join(',', source)}]"; - } - - /// - /// Returns true if the collection contains an item with the ip address, - /// or the ip address falls within any of the collection's network ranges. - /// - /// The . - /// The item to look for. - /// True if the collection contains the item. - public static bool ContainsAddress(this Collection source, IPAddress item) - { - if (source.Count == 0) + if (address.AddressFamily != AddressFamily.InterNetworkV6) { return false; } - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - - if (item.IsIPv4MappedToIPv6) - { - item = item.MapToIPv4(); - } + // GetAddressBytes + Span octet = stackalloc byte[16]; + address.TryWriteBytes(octet, out _); + uint word = (uint)(octet[0] << 8) + octet[1]; - foreach (var i in source) - { - if (i.Contains(item)) - { - return true; - } - } + return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link. + } - return false; + /// + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// + /// Subnet mask in CIDR notation. + /// IPv4 or IPv6 family. + /// String value of the subnet mask in dotted decimal notation. + public static IPAddress CidrToMask(byte cidr, AddressFamily family) + { + uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr); + addr = ((addr & 0xff000000) >> 24) + | ((addr & 0x00ff0000) >> 8) + | ((addr & 0x0000ff00) << 8) + | ((addr & 0x000000ff) << 24); + return new IPAddress(addr); } /// - /// Returns true if the collection contains an item with the ip address, - /// or the ip address falls within any of the collection's network ranges. + /// Convert a subnet mask to a CIDR. IPv4 only. + /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. /// - /// The . - /// The item to look for. - /// True if the collection contains the item. - public static bool ContainsAddress(this Collection source, IPObject item) + /// Subnet mask. + /// Byte CIDR representing the mask. + public static byte MaskToCidr(IPAddress mask) { - if (source.Count == 0) + if (mask == null) { - return false; + throw new ArgumentNullException(nameof(mask)); } - if (item == null) + byte cidrnet = 0; + if (!mask.Equals(IPAddress.Any)) { - throw new ArgumentNullException(nameof(item)); - } + // GetAddressBytes + Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; + mask.TryWriteBytes(bytes, out _); - foreach (var i in source) - { - if (i.Contains(item)) + var zeroed = false; + for (var i = 0; i < bytes.Length; i++) { - return true; + 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 false; + return cidrnet; } /// - /// Compares two Collection{IPObject} objects. The order is ignored. + /// Converts an IPAddress into a string. + /// Ipv6 addresses are returned in [ ], with their scope removed. /// - /// The . - /// Item to compare to. - /// True if both are equal. - public static bool Compare(this Collection source, Collection dest) + /// Address to convert. + /// URI safe conversion of the address. + public static string FormatIpString(IPAddress? address) { - if (dest == null || source.Count != dest.Count) + if (address == null) { - return false; + return string.Empty; } - foreach (var sourceItem in source) + var str = address.ToString(); + if (address.AddressFamily == AddressFamily.InterNetworkV6) { - bool found = false; - foreach (var destItem in dest) + int i = str.IndexOf('%', StringComparison.Ordinal); + if (i != -1) { - if (sourceItem.Equals(destItem)) - { - found = true; - break; - } + str = str.Substring(0, i); } - if (!found) - { - return false; - } + return $"[{str}]"; } - return true; + return str; } /// - /// Returns a collection containing the subnets of this collection given. + /// Attempts to parse a host string. /// - /// The . - /// Collection{IPObject} object containing the subnets. - public static Collection AsNetworks(this Collection source) + /// Host name to parse. + /// Object representing the string, if it has successfully been parsed. + /// true if IPv4 is enabled. + /// true if IPv6 is enabled. + /// true if the parsing is successful, false if not. + public static bool TryParseHost(string host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIpv4Enabled = true, bool isIpv6Enabled = false) { - if (source == null) + if (string.IsNullOrWhiteSpace(host)) { - throw new ArgumentNullException(nameof(source)); + addresses = Array.Empty(); + return false; } - Collection res = new Collection(); + host = host.Trim(); - foreach (IPObject i in source) + // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. + if (host[0] == '[') { - if (i is IPNetAddress nw) - { - // Add the subnet calculated from the interface address/mask. - var na = nw.NetworkAddress; - na.Tag = i.Tag; - res.AddItem(na); - } - else if (i is IPHost ipHost) + int i = host.IndexOf(']', StringComparison.Ordinal); + if (i != -1) { - // Flatten out IPHost and add all its ip addresses. - foreach (var addr in ipHost.GetAddresses()) - { - IPNetAddress host = new IPNetAddress(addr) - { - Tag = i.Tag - }; - - res.AddItem(host); - } + return TryParseHost(host.Remove(i)[1..], out addresses); } - } - - return res; - } - /// - /// Excludes all the items from this list that are found in excludeList. - /// - /// The . - /// Items to exclude. - /// Collection is a network collection. - /// A new collection, with the items excluded. - public static Collection Exclude(this Collection source, Collection excludeList, bool isNetwork) - { - if (source.Count == 0 || excludeList == null) - { - return new Collection(source); + addresses = Array.Empty(); + return false; } - Collection results = new Collection(); + var hosts = host.Split(':'); - bool found; - foreach (var outer in source) + if (hosts.Length <= 2) { - found = false; + // 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 + string pattern = @"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$"; - foreach (var inner in excludeList) + // Is hostname or hostname:port + if (Regex.IsMatch(hosts[0], pattern)) { - if (outer.Equals(inner)) + try + { + addresses = Dns.GetHostAddresses(hosts[0]); + return true; + } + catch (SocketException) { - found = true; - break; + // Log and then ignore socket errors, as the result value will just be an empty array. + Console.WriteLine("GetHostAddresses failed."); } } - if (!found) - { - results.AddItem(outer, isNetwork); - } - } + // Is an IP4 or IP4:port + host = hosts[0].Split('/')[0]; - return results; - } + if (IPAddress.TryParse(host, out var address)) + { + if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIpv4Enabled && isIpv6Enabled)) || + ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIpv4Enabled && !isIpv6Enabled))) + { + addresses = Array.Empty(); + return false; + } - /// - /// Returns all items that co-exist in this object and target. - /// - /// The . - /// Collection to compare with. - /// A collection containing all the matches. - public static Collection ThatAreContainedInNetworks(this Collection source, Collection target) - { - if (source.Count == 0) - { - return new Collection(); - } + addresses = new[] { address }; - if (target == null) - { - throw new ArgumentNullException(nameof(target)); + // Host name is an ip4 address, so fake resolve. + return true; + } } - - Collection nc = new Collection(); - - foreach (IPObject i in source) + else if (hosts.Length <= 9 && IPAddress.TryParse(host.Split('/')[0], out var address)) // 8 octets + port { - if (target.ContainsAddress(i)) - { - nc.AddItem(i); - } + addresses = new[] { address }; + return true; } - return nc; + addresses = Array.Empty(); + return false; } } } -- cgit v1.2.3 From 64ffd5fd9526762e27d97e13c59cc6552c97e7bc Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 09:45:57 +0200 Subject: Move subnet parser to NetworkExtensions --- Jellyfin.Networking/Manager/NetworkManager.cs | 72 ++------------------------- MediaBrowser.Common/Net/NetworkExtensions.cs | 58 ++++++++++++++++++++- 2 files changed, 62 insertions(+), 68 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index d9ef2c6a4..e9e3e1802 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -326,8 +326,8 @@ namespace Jellyfin.Networking.Manager // Get configuration options string[] subnets = config.LocalNetworkSubnets; - _ = TryParseSubnets(subnets, out _lanSubnets, false); - _ = TryParseSubnets(subnets, out _excludedSubnets, true); + _ = NetworkExtensions.TryParseSubnets(subnets, out _lanSubnets, false); + _ = NetworkExtensions.TryParseSubnets(subnets, out _excludedSubnets, true); if (_lanSubnets.Count == 0) { @@ -419,7 +419,7 @@ namespace Jellyfin.Networking.Manager if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First())) { // Parse all IPs with netmask to a subnet - _ = TryParseSubnets(remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); + _ = NetworkExtensions.TryParseSubnets(remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); // Parse everything else as an IP and construct subnet with a single IP var ips = remoteIPFilter.Where(x => !x.Contains('/', StringComparison.OrdinalIgnoreCase)); @@ -595,68 +595,6 @@ namespace Jellyfin.Networking.Manager return false; } - /// - /// Try parsing an array of strings into subnets, respecting exclusions. - /// - /// Input string to be parsed. - /// Collection of . - /// Boolean signaling if negated or not negated values should be parsed. - /// True if parsing was successful. - public bool TryParseSubnets(string[] values, out Collection result, bool negated = false) - { - result = new Collection(); - - if (values == null || values.Length == 0) - { - return false; - } - - for (int a = 0; a < values.Length; a++) - { - string[] v = values[a].Trim().Split("/"); - - try - { - var address = IPAddress.None; - if (negated && v[0].StartsWith('!')) - { - _ = IPAddress.TryParse(v[0][1..], out address); - } - else if (!negated) - { - _ = IPAddress.TryParse(v[0][0..], out address); - } - - if (address != IPAddress.None && address != null) - { - if (int.TryParse(v[1], out var netmask)) - { - result.Add(new IPNetwork(address, netmask)); - } - else if (address.AddressFamily == AddressFamily.InterNetwork) - { - result.Add(new IPNetwork(address, 32)); - } - else if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - result.Add(new IPNetwork(address, 128)); - } - } - } - catch (ArgumentException e) - { - _logger.LogWarning(e, "Ignoring LAN value {Value}.", v); - } - } - - if (result.Count > 0) - { - return true; - } - - return false; - } - /// public bool HasRemoteAccess(IPAddress remoteIp) { @@ -802,12 +740,12 @@ namespace Jellyfin.Networking.Manager if (source != null) { - if (IsIpv4Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) + if (IsIpv4Enabled && !IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) { _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); } - if (IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) + if (!IsIpv4Enabled && IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) { _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 55ec322f4..4cba1c99f 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,5 +1,6 @@ +using Microsoft.AspNetCore.HttpOverrides; using System; -using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Sockets; @@ -136,6 +137,61 @@ namespace MediaBrowser.Common.Net return str; } + /// + /// Try parsing an array of strings into subnets, respecting exclusions. + /// + /// Input string to be parsed. + /// Collection of . + /// Boolean signaling if negated or not negated values should be parsed. + /// True if parsing was successful. + public static bool TryParseSubnets(string[] values, out Collection result, bool negated = false) + { + result = new Collection(); + + if (values == null || values.Length == 0) + { + return false; + } + + for (int a = 0; a < values.Length; a++) + { + string[] v = values[a].Trim().Split("/"); + + var address = IPAddress.None; + if (negated && v[0].StartsWith('!')) + { + _ = IPAddress.TryParse(v[0][1..], out address); + } + else if (!negated) + { + _ = IPAddress.TryParse(v[0][0..], out address); + } + + if (address != IPAddress.None && address != null) + { + if (int.TryParse(v[1], out var netmask)) + { + result.Add(new IPNetwork(address, netmask)); + } + else if (address.AddressFamily == AddressFamily.InterNetwork) + { + result.Add(new IPNetwork(address, 32)); + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + result.Add(new IPNetwork(address, 128)); + } + } + } + + if (result.Count > 0) + { + return true; + } + + return false; + } + /// /// Attempts to parse a host string. /// -- cgit v1.2.3 From a492082f4e015d6d38368c4ac05d39d236387214 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 11:47:48 +0200 Subject: Apply review suggestions and fix build --- .../Extensions/ApiServiceCollectionExtensions.cs | 5 +++++ MediaBrowser.Common/Net/IPData.cs | 17 +++++------------ MediaBrowser.Common/Net/NetworkExtensions.cs | 10 +++++----- tests/Jellyfin.Server.Tests/ParseNetworkTests.cs | 8 ++++---- 4 files changed, 19 insertions(+), 21 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 507395106..a393b80db 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -372,6 +372,11 @@ namespace Jellyfin.Server.Extensions return; } + if (addr.IsIPv4MappedToIPv6) + { + addr = addr.MapToIPv4(); + } + if (prefixLength == 32) { options.KnownProxies.Add(addr); diff --git a/MediaBrowser.Common/Net/IPData.cs b/MediaBrowser.Common/Net/IPData.cs index 3c6adc7e8..6901d6ad8 100644 --- a/MediaBrowser.Common/Net/IPData.cs +++ b/MediaBrowser.Common/Net/IPData.cs @@ -14,13 +14,12 @@ namespace MediaBrowser.Common.Net /// /// An . /// The . - public IPData( - IPAddress address, - IPNetwork? subnet) + /// The object's name. + public IPData(IPAddress address, IPNetwork? subnet, string name) { Address = address; Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128)); - Name = string.Empty; + Name = name; } /// @@ -28,15 +27,9 @@ namespace MediaBrowser.Common.Net /// /// An . /// The . - /// The object's name. - public IPData( - IPAddress address, - IPNetwork? subnet, - string name) + public IPData(IPAddress address, IPNetwork? subnet) + : this(address, subnet, string.Empty) { - Address = address; - Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128)); - Name = name; } /// diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 4cba1c99f..ae1e47ccc 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -13,6 +13,10 @@ namespace MediaBrowser.Common.Net /// public static class NetworkExtensions { + // Use regular expression as CheckHostName isn't RFC5892 compliant. + // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation + private static readonly Regex _fqdnRegex = new Regex(@"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$"); + /// /// Returns true if the IPAddress contains an IP6 Local link address. /// @@ -227,12 +231,8 @@ namespace MediaBrowser.Common.Net if (hosts.Length <= 2) { - // 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 - string pattern = @"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$"; - // Is hostname or hostname:port - if (Regex.IsMatch(hosts[0], pattern)) + if (_fqdnRegex.IsMatch(hosts[0])) { try { diff --git a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs index a1bdfa31b..fc5f5f4c6 100644 --- a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs @@ -21,9 +21,9 @@ namespace Jellyfin.Server.Tests data.Add( true, true, - new string[] { "192.168.t", "127.0.0.1", "1234.1232.12.1234" }, - new IPAddress[] { IPAddress.Loopback.MapToIPv6() }, - Array.Empty()); + new string[] { "192.168.t", "127.0.0.1", "::1", "1234.1232.12.1234" }, + new IPAddress[] { IPAddress.Loopback, }, + new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) }); data.Add( true, @@ -64,7 +64,7 @@ namespace Jellyfin.Server.Tests true, true, new string[] { "localhost" }, - new IPAddress[] { IPAddress.Loopback.MapToIPv6() }, + new IPAddress[] { IPAddress.Loopback }, new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) }); return data; } -- cgit v1.2.3 From 2281b8c997dff0fa148bf0f193b37664420aca3e Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 14:29:30 +0200 Subject: Move away from using Collection, simplify code, add proper ordering --- Emby.Dlna/Main/DlnaEntryPoint.cs | 2 +- .../Configuration/NetworkConfiguration.cs | 4 +- Jellyfin.Networking/Manager/NetworkManager.cs | 54 +++++++++++----------- .../CreateNetworkConfiguration.cs | 2 +- MediaBrowser.Common/Net/INetworkManager.cs | 13 +++--- MediaBrowser.Common/Net/NetworkExtensions.cs | 6 +-- .../Jellyfin.Networking.Tests/NetworkParseTests.cs | 8 ++-- 7 files changed, 42 insertions(+), 47 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 7bc761b71..90c985a81 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -293,7 +293,7 @@ namespace Emby.Dlna.Main if (bindAddresses.Count == 0) { // No interfaces returned, so use loopback. - bindAddresses = _networkManager.GetLoopbacks(); + bindAddresses = _networkManager.GetLoopbacks().ToList(); } foreach (var address in bindAddresses) diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 0ac55c986..be8dc738d 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -151,9 +151,9 @@ namespace Jellyfin.Networking.Configuration public bool IgnoreVirtualInterfaces { get; set; } = true; /// - /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. . + /// 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. . /// - public string VirtualInterfaceNames { get; set; } = "vEthernet*"; + public string VirtualInterfaceNames { get; set; } = "veth"; /// /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor. diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index e9e3e1802..757b5994b 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Net; @@ -47,7 +46,7 @@ namespace Jellyfin.Networking.Manager /// private readonly Dictionary _publishedServerUrls; - private Collection _remoteAddressFilter; + private List _remoteAddressFilter; /// /// Used to stop "event-racing conditions". @@ -58,12 +57,12 @@ namespace Jellyfin.Networking.Manager /// Unfiltered user defined LAN subnets () /// or internal interface network subnets if undefined by user. /// - private Collection _lanSubnets; + private List _lanSubnets; /// /// User defined list of subnets to excluded from the LAN. /// - private Collection _excludedSubnets; + private List _excludedSubnets; /// /// List of interfaces to bind to. @@ -95,7 +94,7 @@ namespace Jellyfin.Networking.Manager _macAddresses = new List(); _publishedServerUrls = new Dictionary(); _eventFireLock = new object(); - _remoteAddressFilter = new Collection(); + _remoteAddressFilter = new List(); UpdateSettings(_configurationManager.GetNetworkConfiguration()); @@ -225,8 +224,8 @@ namespace Jellyfin.Networking.Manager { try { - IPInterfaceProperties ipProperties = adapter.GetIPProperties(); - PhysicalAddress mac = adapter.GetPhysicalAddress(); + var ipProperties = adapter.GetIPProperties(); + var mac = adapter.GetPhysicalAddress(); // Populate MAC list if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && PhysicalAddress.None.Equals(mac)) @@ -235,7 +234,7 @@ namespace Jellyfin.Networking.Manager } // Populate interface list - foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses) + foreach (var info in ipProperties.UnicastAddresses) { if (IsIpv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) { @@ -364,8 +363,8 @@ namespace Jellyfin.Networking.Manager // Use explicit bind addresses if (config.LocalNetworkAddresses.Length > 0) { - _bindAddresses = config.LocalNetworkAddresses.Select(p => IPAddress.TryParse(p, out var address) - ? address + _bindAddresses = config.LocalNetworkAddresses.Select(p => IPAddress.TryParse(p, out var addresses) + ? addresses : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)).Select(x => x.Address).FirstOrDefault() ?? IPAddress.None)).ToList(); _bindAddresses.RemoveAll(x => x == IPAddress.None); } @@ -525,13 +524,11 @@ namespace Jellyfin.Networking.Manager var address = IPAddress.Parse(split[0]); var network = new IPNetwork(address, int.Parse(split[1], CultureInfo.InvariantCulture)); var index = int.Parse(parts[1], CultureInfo.InvariantCulture); - if (address.AddressFamily == AddressFamily.InterNetwork) + if (address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6) { - _interfaces.Add(new IPData(address, network, parts[2])); - } - else if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - _interfaces.Add(new IPData(address, network, parts[2])); + var data = new IPData(address, network, parts[2]); + data.Index = index; + _interfaces.Add(data); } } } @@ -562,9 +559,9 @@ namespace Jellyfin.Networking.Manager } /// - public bool TryParseInterface(string intf, out Collection result) + public bool TryParseInterface(string intf, out List result) { - result = new Collection(); + result = new List(); if (string.IsNullOrEmpty(intf)) { return false; @@ -573,7 +570,7 @@ namespace Jellyfin.Networking.Manager if (_interfaces != null) { // Match all interfaces starting with names starting with token - var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf.ToLowerInvariant(), StringComparison.OrdinalIgnoreCase)); + var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf.ToLowerInvariant(), StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index); if (matchedInterfaces.Any()) { _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); @@ -626,14 +623,14 @@ namespace Jellyfin.Networking.Manager } /// - public IReadOnlyCollection GetMacAddresses() + public IReadOnlyList GetMacAddresses() { // Populated in construction - so always has values. return _macAddresses; } /// - public List GetLoopbacks() + public IReadOnlyList GetLoopbacks() { var loopbackNetworks = new List(); if (IsIpv4Enabled) @@ -650,7 +647,7 @@ namespace Jellyfin.Networking.Manager } /// - public List GetAllBindInterfaces(bool individualInterfaces = false) + public IReadOnlyList GetAllBindInterfaces(bool individualInterfaces = false) { if (_bindAddresses.Count == 0) { @@ -816,7 +813,7 @@ namespace Jellyfin.Networking.Manager } /// - public List GetInternalBindAddresses() + public IReadOnlyList GetInternalBindAddresses() { if (_bindAddresses.Count == 0) { @@ -833,7 +830,8 @@ namespace Jellyfin.Networking.Manager // Select all local bind addresses return _interfaces.Where(x => _bindAddresses.Contains(x.Address)) .Where(x => IsInLocalNetwork(x.Address)) - .OrderBy(x => x.Index).ToList(); + .OrderBy(x => x.Index) + .ToList(); } /// @@ -892,7 +890,7 @@ namespace Jellyfin.Networking.Manager interfaces = interfaces.Where(x => IsInLocalNetwork(x.Address)).ToList(); } - foreach (var intf in _interfaces) + foreach (var intf in interfaces) { if (intf.Subnet.Contains(address)) { @@ -942,7 +940,7 @@ namespace Jellyfin.Networking.Manager foreach (var data in validPublishedServerUrls) { // Get address interface - var intf = _interfaces.FirstOrDefault(s => s.Subnet.Contains(data.Key.Address)); + var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(s => s.Subnet.Contains(data.Key.Address)); // Remaining. Match anything. if (data.Key.Address.Equals(IPAddress.Broadcast)) @@ -1017,7 +1015,7 @@ namespace Jellyfin.Networking.Manager defaultGateway = addr; } - var intf = _interfaces.Where(x => x.Subnet.Contains(addr)).FirstOrDefault(); + var intf = _interfaces.Where(x => x.Subnet.Contains(addr)).OrderBy(x => x.Index).FirstOrDefault(); if (bindAddress == null && intf != null && intf.Subnet.Contains(source)) { @@ -1082,7 +1080,7 @@ namespace Jellyfin.Networking.Manager { result = string.Empty; // Get the first WAN interface address that isn't a loopback. - var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address)); + var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address)).OrderBy(x => x.Index); IPAddress? hasResult = null; // Does the request originate in one of the interface subnets? diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs index ceeaa26e6..b67017281 100644 --- a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs +++ b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs @@ -114,7 +114,7 @@ public class CreateNetworkConfiguration : IMigrationRoutine public bool IgnoreVirtualInterfaces { get; set; } = true; - public string VirtualInterfaceNames { get; set; } = "veth*"; + public string VirtualInterfaceNames { get; set; } = "veth"; public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 9f4853557..bb0e2dcb3 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Net; using System.Net.NetworkInformation; using Microsoft.AspNetCore.Http; @@ -34,13 +33,13 @@ namespace MediaBrowser.Common.Net /// If all the interfaces are specified, and none are excluded, it returns zero items /// to represent any address. /// When false, return or for all interfaces. - List GetAllBindInterfaces(bool individualInterfaces = false); + IReadOnlyList GetAllBindInterfaces(bool individualInterfaces = false); /// - /// Returns a collection containing the loopback interfaces. + /// Returns a list containing the loopback interfaces. /// /// List{IPData}. - List GetLoopbacks(); + IReadOnlyList GetLoopbacks(); /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) @@ -97,7 +96,7 @@ namespace MediaBrowser.Common.Net /// Get a list of all the MAC addresses associated with active interfaces. /// /// List of MAC addresses. - IReadOnlyCollection GetMacAddresses(); + IReadOnlyList GetMacAddresses(); /// /// Returns true if the address is part of the user defined LAN. @@ -122,13 +121,13 @@ namespace MediaBrowser.Common.Net /// Interface name. /// Resultant object's ip addresses, if successful. /// Success of the operation. - bool TryParseInterface(string intf, out Collection? result); + bool TryParseInterface(string intf, out List? result); /// /// Returns all the internal Bind interface addresses. /// /// An internal list of interfaces addresses. - List GetInternalBindAddresses(); + IReadOnlyList GetInternalBindAddresses(); /// /// Checks to see if has access. diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index ae1e47ccc..316c2ebcd 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,6 +1,6 @@ using Microsoft.AspNetCore.HttpOverrides; using System; -using System.Collections.ObjectModel; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Sockets; @@ -148,9 +148,9 @@ namespace MediaBrowser.Common.Net /// Collection of . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. - public static bool TryParseSubnets(string[] values, out Collection result, bool negated = false) + public static bool TryParseSubnets(string[] values, out List result, bool negated = false) { - result = new Collection(); + result = new List(); if (values == null || values.Length == 0) { diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 5b9739dd3..c45a9c9f5 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -1,5 +1,5 @@ using System; -using System.Collections.ObjectModel; +using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; @@ -49,8 +49,6 @@ namespace Jellyfin.Networking.Tests { EnableIPV6 = true, EnableIPV4 = true, - IgnoreVirtualInterfaces = true, - VirtualInterfaceNames = "veth", LocalNetworkSubnets = lan?.Split(';') ?? throw new ArgumentNullException(nameof(lan)) }; @@ -208,7 +206,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - _ = nm.TryParseInterface(result, out Collection? resultObj); + _ = nm.TryParseInterface(result, out List? resultObj); // Check to see if dns resolution is working. If not, skip test. _ = NetworkExtensions.TryParseHost(source, out var host); @@ -277,7 +275,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - if (nm.TryParseInterface(result, out Collection? resultObj) && resultObj != null) + if (nm.TryParseInterface(result, out List? resultObj) && resultObj != null) { // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks). result = resultObj.First().Address.ToString(); -- cgit v1.2.3 From 4aec41752f63594e169511a314f8f86a0dde9c35 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Fri, 14 Oct 2022 10:25:57 +0200 Subject: Apply review suggestions --- Emby.Dlna/Main/DlnaEntryPoint.cs | 8 +-- Jellyfin.Networking/Manager/NetworkManager.cs | 58 +++++++++++----------- .../Extensions/ApiServiceCollectionExtensions.cs | 4 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 54 +++++++++++++++++++- RSSDP/SsdpCommunicationsServer.cs | 6 +-- 5 files changed, 92 insertions(+), 38 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 0aea7855a..7c26262fe 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -286,10 +286,10 @@ namespace Emby.Dlna.Main // Only get bind addresses in LAN var bindAddresses = _networkManager - .GetInternalBindAddresses() - .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork - || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)) - .ToList(); + .GetInternalBindAddresses() + .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork + || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)) + .ToList(); if (bindAddresses.Count == 0) { diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 333afd748..42b66bbed 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; +using System.Threading; using System.Threading.Tasks; using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Configuration; @@ -34,7 +35,7 @@ namespace Jellyfin.Networking.Manager private readonly IConfigurationManager _configurationManager; - private readonly object _eventFireLock; + private readonly SemaphoreSlim _networkEvent; /// /// Holds the published server URLs and the IPs to use them on. @@ -86,7 +87,7 @@ namespace Jellyfin.Networking.Manager _interfaces = new List(); _macAddresses = new List(); _publishedServerUrls = new Dictionary(); - _eventFireLock = new object(); + _networkEvent = new SemaphoreSlim(1, 1); _remoteAddressFilter = new List(); UpdateSettings(_configurationManager.GetNetworkConfiguration()); @@ -143,7 +144,7 @@ namespace Jellyfin.Networking.Manager private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) { _logger.LogDebug("Network availability changed."); - OnNetworkChanged(); + HandleNetworkChange(); } /// @@ -154,35 +155,34 @@ namespace Jellyfin.Networking.Manager private void OnNetworkAddressChanged(object? sender, EventArgs e) { _logger.LogDebug("Network address change detected."); - OnNetworkChanged(); + HandleNetworkChange(); } /// /// Triggers our event, and re-loads interface information. /// - private void OnNetworkChanged() + private void HandleNetworkChange() { - lock (_eventFireLock) + _networkEvent.Wait(); + if (!_eventfire) { - 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; - OnNetworkChangeAsync().GetAwaiter().GetResult(); - } + _logger.LogDebug("Network Address Change Event."); + // As network events tend to fire one after the other only fire once every second. + _eventfire = true; + OnNetworkChange(); } + + _networkEvent.Release(); } /// - /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. + /// Waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. /// - /// A representing the asynchronous operation. - private async Task OnNetworkChangeAsync() + private void OnNetworkChange() { try { - await Task.Delay(2000).ConfigureAwait(false); + Thread.Sleep(2000); var networkConfig = _configurationManager.GetNetworkConfiguration(); InitialiseLan(networkConfig); InitialiseInterfaces(); @@ -234,7 +234,7 @@ namespace Jellyfin.Networking.Manager { var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); interfaceObject.Index = ipProperties.GetIPv4Properties().Index; - interfaceObject.Name = adapter.Name.ToLowerInvariant(); + interfaceObject.Name = adapter.Name; _interfaces.Add(interfaceObject); } @@ -242,7 +242,7 @@ namespace Jellyfin.Networking.Manager { var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name); interfaceObject.Index = ipProperties.GetIPv6Properties().Index; - interfaceObject.Name = adapter.Name.ToLowerInvariant(); + interfaceObject.Name = adapter.Name; _interfaces.Add(interfaceObject); } @@ -362,11 +362,10 @@ namespace Jellyfin.Networking.Manager { // Remove potentially exisiting * and split config string into prefixes var virtualInterfacePrefixes = config.VirtualInterfaceNames - .Select(i => i.ToLowerInvariant() - .Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase)); + .Select(i => i.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase)); // Check all interfaces for matches against the prefixes and remove them - if (_interfaces.Count > 0 && virtualInterfacePrefixes.Any()) + if (_interfaces.Count > 0) { foreach (var virtualInterfacePrefix in virtualInterfacePrefixes) { @@ -548,6 +547,7 @@ namespace Jellyfin.Networking.Manager _configurationManager.NamedConfigurationUpdated -= ConfigurationUpdated; NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged; NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged; + _networkEvent.Dispose(); } _disposed = true; @@ -566,7 +566,7 @@ namespace Jellyfin.Networking.Manager if (_interfaces != null) { // Match all interfaces starting with names starting with token - var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf.ToLowerInvariant(), StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index); + var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf, StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index); if (matchedInterfaces.Any()) { _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); @@ -609,7 +609,7 @@ namespace Jellyfin.Networking.Manager return false; } } - else if (!_lanSubnets.Where(x => x.Contains(remoteIp)).Any()) + else if (!_lanSubnets.Any(x => x.Contains(remoteIp))) { // Remote not enabled. So everyone should be LAN. return false; @@ -875,10 +875,12 @@ namespace Jellyfin.Networking.Manager bindPreference = string.Empty; port = null; - var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any)).ToList(); - validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.IPv6Any))); - validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Subnet.Contains(source))); - validPublishedServerUrls = validPublishedServerUrls.GroupBy(x => x.Key).Select(y => y.First()).ToList(); + var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any) + || x.Key.Address.Equals(IPAddress.IPv6Any) + || x.Key.Subnet.Contains(source)) + .GroupBy(x => x.Key) + .Select(y => y.First()) + .ToList(); // Check for user override. foreach (var data in validPublishedServerUrls) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 25516271c..a1adddcbb 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -348,9 +348,9 @@ namespace Jellyfin.Server.Extensions { AddIpAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } - else if (NetworkExtensions.TryParseSubnets(new[] { allowedProxies[i] }, out var subnets)) + else if (NetworkExtensions.TryParseSubnet(allowedProxies[i], out var subnet)) { - foreach (var subnet in subnets) + if (subnet != null) { AddIpAddress(config, options, subnet.Prefix, subnet.PrefixLength); } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 3d7d58b27..d7632c0de 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -138,7 +138,7 @@ namespace MediaBrowser.Common.Net /// /// Try parsing an array of strings into subnets, respecting exclusions. /// - /// Input string to be parsed. + /// Input string array to be parsed. /// Collection of . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. @@ -190,6 +190,58 @@ namespace MediaBrowser.Common.Net return false; } + /// + /// Try parsing a string into a subnet, respecting exclusions. + /// + /// Input string to be parsed. + /// An . + /// Boolean signaling if negated or not negated values should be parsed. + /// True if parsing was successful. + public static bool TryParseSubnet(string value, out IPNetwork? result, bool negated = false) + { + result = null; + + if (string.IsNullOrEmpty(value)) + { + return false; + } + + string[] v = value.Trim().Split("/"); + + var address = IPAddress.None; + if (negated && v[0].StartsWith('!')) + { + _ = IPAddress.TryParse(v[0][1..], out address); + } + else if (!negated) + { + _ = IPAddress.TryParse(v[0][0..], out address); + } + + if (address != IPAddress.None && address != null) + { + if (int.TryParse(v[1], out var netmask)) + { + result = new IPNetwork(address, netmask); + } + else if (address.AddressFamily == AddressFamily.InterNetwork) + { + result = new IPNetwork(address, 32); + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + result = new IPNetwork(address, 128); + } + } + + if (result != null) + { + return true; + } + + return false; + } + /// /// Attempts to parse a host string. /// diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index 92c9c83c0..da357546d 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -117,7 +117,7 @@ namespace Rssdp.Infrastructure { try { - _BroadcastListenSockets = ListenForBroadcastsAsync(); + _BroadcastListenSockets = ListenForBroadcasts(); } catch (SocketException ex) { @@ -333,7 +333,7 @@ namespace Rssdp.Infrastructure return Task.CompletedTask; } - private List ListenForBroadcastsAsync() + private List ListenForBroadcasts() { var sockets = new List(); if (_enableMultiSocketBinding) @@ -352,7 +352,7 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.LogError(ex, "Error in ListenForBroadcastsAsync. IPAddress: {0}", address); + _logger.LogError(ex, "Error in ListenForBroadcasts. IPAddress: {0}", address); } } } -- cgit v1.2.3 From 87d0158a4af9d8c982736cbae77019fa6dd03126 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Sat, 15 Oct 2022 17:27:37 +0200 Subject: Fix autodiscovery --- .../EntryPoints/UdpServerEntryPoint.cs | 9 +++- Jellyfin.Networking/Manager/NetworkManager.cs | 59 ++++++++++------------ MediaBrowser.Common/Net/NetworkExtensions.cs | 32 +++++++++++- 3 files changed, 67 insertions(+), 33 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 82c6abb8c..01a987b6a 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -79,6 +79,10 @@ namespace Emby.Server.Implementations.EntryPoints { if (_enableMultiSocketBinding) { + // Add global broadcast socket + _udpServers.Add(new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Broadcast, PortNumber)); + + // Add bind address specific broadcast sockets foreach (var bindAddress in _networkManager.GetInternalBindAddresses()) { if (bindAddress.AddressFamily == AddressFamily.InterNetworkV6) @@ -87,7 +91,10 @@ namespace Emby.Server.Implementations.EntryPoints continue; } - _udpServers.Add(new UdpServer(_logger, _appHost, _config, bindAddress.Address, PortNumber)); + var broadcastAddress = NetworkExtensions.GetBroadcastAddress(bindAddress.Subnet); + _logger.LogDebug("Binding UDP server to {Address}", broadcastAddress.ToString()); + + _udpServers.Add(new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber)); } } else diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 42b66bbed..3c347461a 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -280,7 +280,7 @@ namespace Jellyfin.Networking.Manager } _logger.LogDebug("Discovered {0} interfaces.", _interfaces.Count); - _logger.LogDebug("Interfaces addresses : {0}", _interfaces.Select(s => s.Address).ToString()); + _logger.LogDebug("Interfaces addresses : {0}", _interfaces.Select(s => s.Address.ToString())); } } @@ -726,20 +726,11 @@ namespace Jellyfin.Networking.Manager } bool isExternal = !_lanSubnets.Any(network => network.Contains(source)); - _logger.LogDebug("GetBindInterface with source. External: {IsExternal}:", isExternal); + _logger.LogDebug("GetBindInterface with source {Source}. External: {IsExternal}:", source, isExternal); - if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) + if (MatchesPublishedServerUrl(source, isExternal, out result)) { - if (port != null) - { - _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port); - } - else - { - _logger.LogInformation("{Source}: Using BindAddress {Address}", source, res); - } - - return res; + return result; } // No preference given, so move on to bind addresses. @@ -868,41 +859,37 @@ namespace Jellyfin.Networking.Manager /// IP source address to use. /// True if the source is in an external subnet. /// The published server URL that matches the source address. - /// The resultant port, if one exists. /// true if a match is found, false otherwise. - private bool MatchesPublishedServerUrl(IPAddress 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)) .GroupBy(x => x.Key) - .Select(y => y.First()) + .Select(x => x.First()) + .OrderBy(x => x.Key.Address.Equals(IPAddress.Any) + || x.Key.Address.Equals(IPAddress.IPv6Any)) .ToList(); // Check for user override. foreach (var data in validPublishedServerUrls) { - // Get address interface - var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(s => s.Subnet.Contains(data.Key.Address)); + // Get address interface. + var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(x => data.Key.Subnet.Contains(x.Address)); - // Remaining. Match anything. - if (data.Key.Address.Equals(IPAddress.Broadcast)) - { - bindPreference = data.Value; - break; - } - else if ((data.Key.Address.Equals(IPAddress.Any) || data.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet) + if (isInExternalSubnet && (data.Key.Address.Equals(IPAddress.Any) || data.Key.Address.Equals(IPAddress.IPv6Any))) { // External. bindPreference = data.Value; break; } - else if (intf?.Address != null) + + if (intf?.Address != null) { - // Match ip address. + // Match IP address. bindPreference = data.Value; break; } @@ -910,6 +897,7 @@ namespace Jellyfin.Networking.Manager if (string.IsNullOrEmpty(bindPreference)) { + _logger.LogInformation("{Source}: No matching bind address override found", source); return false; } @@ -924,6 +912,15 @@ namespace Jellyfin.Networking.Manager } } + if (port != null) + { + _logger.LogInformation("{Source}: Matching bind address override found {Address}:{Port}", source, bindPreference, port); + } + else + { + _logger.LogInformation("{Source}: Matching bind address override found {Address}", source, bindPreference); + } + return true; } @@ -967,12 +964,12 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching external bind interface: {Result}", source, result); + _logger.LogDebug("{Source}: External request received, matching external bind interface found: {Result}", source, result); return true; } } - _logger.LogWarning("{Source}: External request received, no external interface bind found, trying internal interfaces.", source); + _logger.LogWarning("{Source}: External request received, no matching external bind interface found, trying internal interfaces.", source); } else { @@ -987,7 +984,7 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogWarning("{Source}: Request received, matching internal interface bind found: {Result}", source, result); + _logger.LogDebug("{Source}: Internal request received, matching internal bind interface found: {Result}", source, result); return true; } } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index d7632c0de..1c2b65346 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -56,7 +56,23 @@ namespace MediaBrowser.Common.Net /// String value of the subnet mask in dotted decimal notation. public static IPAddress CidrToMask(byte cidr, AddressFamily family) { - uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr); + uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? 32 : 128) - cidr); + addr = ((addr & 0xff000000) >> 24) + | ((addr & 0x00ff0000) >> 8) + | ((addr & 0x0000ff00) << 8) + | ((addr & 0x000000ff) << 24); + return new IPAddress(addr); + } + + /// + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// + /// Subnet mask in CIDR notation. + /// IPv4 or IPv6 family. + /// String value of the subnet mask in dotted decimal notation. + public static IPAddress CidrToMask(int cidr, AddressFamily family) + { + uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? 32 : 128) - cidr); addr = ((addr & 0xff000000) >> 24) | ((addr & 0x00ff0000) >> 8) | ((addr & 0x0000ff00) << 8) @@ -319,5 +335,19 @@ namespace MediaBrowser.Common.Net addresses = Array.Empty(); return false; } + + /// + /// Gets the broadcast address for a . + /// + /// The . + /// The broadcast address. + public static IPAddress GetBroadcastAddress(IPNetwork network) + { + uint ipAddress = BitConverter.ToUInt32(network.Prefix.GetAddressBytes(), 0); + uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0); + uint broadCastIpAddress = ipAddress | ~ipMaskV4; + + return new IPAddress(BitConverter.GetBytes(broadCastIpAddress)); + } } } -- cgit v1.2.3 From f6d6f0367bf62435dfaf7d122415d31977f889aa Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Mon, 17 Oct 2022 15:38:42 +0200 Subject: Properly handle IPs with subnetmasks --- Jellyfin.Networking/Manager/NetworkManager.cs | 54 +++++++++--------- .../Extensions/ApiServiceCollectionExtensions.cs | 2 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 26 ++++++--- .../Jellyfin.Networking.Tests/NetworkParseTests.cs | 65 ++++++++++++---------- 4 files changed, 81 insertions(+), 66 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 7e9fb4df7..4a32423e5 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -295,8 +295,8 @@ namespace Jellyfin.Networking.Manager // Get configuration options string[] subnets = config.LocalNetworkSubnets; - _ = NetworkExtensions.TryParseSubnets(subnets, out _lanSubnets, false); - _ = NetworkExtensions.TryParseSubnets(subnets, out _excludedSubnets, true); + _ = NetworkExtensions.TryParseToSubnets(subnets, out _lanSubnets, false); + _ = NetworkExtensions.TryParseToSubnets(subnets, out _excludedSubnets, true); if (_lanSubnets.Count == 0) { @@ -336,8 +336,8 @@ namespace Jellyfin.Networking.Manager var localNetworkAddresses = config.LocalNetworkAddresses; if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses.First())) { - var bindAddresses = localNetworkAddresses.Select(p => IPAddress.TryParse(p, out var addresses) - ? addresses + 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)) @@ -401,7 +401,7 @@ namespace Jellyfin.Networking.Manager if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First())) { // Parse all IPs with netmask to a subnet - _ = NetworkExtensions.TryParseSubnets(remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); + _ = NetworkExtensions.TryParseToSubnets(remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false); // Parse everything else as an IP and construct subnet with a single IP var ips = remoteIPFilter.Where(x => !x.Contains('/', StringComparison.OrdinalIgnoreCase)); @@ -440,17 +440,17 @@ namespace Jellyfin.Networking.Manager else { var replacement = parts[1].Trim(); - var ipParts = parts[0].Split("/"); - if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase)) + var identifier = parts[0]; + if (string.Equals(identifier, "all", StringComparison.OrdinalIgnoreCase)) { _publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement; } - else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(identifier, "external", StringComparison.OrdinalIgnoreCase)) { _publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; _publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement; } - else if (string.Equals(parts[0], "internal", StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(identifier, "internal", StringComparison.OrdinalIgnoreCase)) { foreach (var lan in _lanSubnets) { @@ -458,17 +458,12 @@ namespace Jellyfin.Networking.Manager _publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement; } } - else if (IPAddress.TryParse(ipParts[0], out IPAddress? result)) + else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result != null) { - var data = new IPData(result, null); - if (ipParts.Length > 1 && int.TryParse(ipParts[1], out var netmask)) - { - data.Subnet = new IPNetwork(result, netmask); - } - + var data = new IPData(result.Prefix, result); _publishedServerUrls[data] = replacement; } - else if (TryParseInterface(ipParts[0], out var ifaces)) + else if (TryParseInterface(identifier, out var ifaces)) { foreach (var iface in ifaces) { @@ -516,15 +511,20 @@ namespace Jellyfin.Networking.Manager foreach (var details in interfaceList) { var parts = details.Split(','); - var split = parts[0].Split("/"); - var address = IPAddress.Parse(split[0]); - var network = new IPNetwork(address, int.Parse(split[1], CultureInfo.InvariantCulture)); - var index = int.Parse(parts[1], CultureInfo.InvariantCulture); - if (address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6) + 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 { - var data = new IPData(address, network, parts[2]); - data.Index = index; - _interfaces.Add(data); + _logger.LogWarning("Could not parse mock interface settings: {Part}", details); } } } @@ -799,9 +799,9 @@ namespace Jellyfin.Networking.Manager /// public bool IsInLocalNetwork(string address) { - if (IPAddress.TryParse(address, out var ep)) + if (NetworkExtensions.TryParseToSubnet(address, out var subnet)) { - return IPAddress.IsLoopback(ep) || (_lanSubnets.Any(x => x.Contains(ep)) && !_excludedSubnets.Any(x => x.Contains(ep))); + return IPAddress.IsLoopback(subnet.Prefix) || (_lanSubnets.Any(x => x.Contains(subnet.Prefix)) && !_excludedSubnets.Any(x => x.Contains(subnet.Prefix))); } if (NetworkExtensions.TryParseHost(address, out var addresses, IsIpv4Enabled, IsIpv6Enabled)) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index a1adddcbb..439147bfd 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -348,7 +348,7 @@ namespace Jellyfin.Server.Extensions { AddIpAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } - else if (NetworkExtensions.TryParseSubnet(allowedProxies[i], out var subnet)) + else if (NetworkExtensions.TryParseToSubnet(allowedProxies[i], out var subnet)) { if (subnet != null) { diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 1c2b65346..e37a5dc6b 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -152,13 +152,14 @@ namespace MediaBrowser.Common.Net } /// - /// Try parsing an array of strings into subnets, respecting exclusions. + /// Try parsing an array of strings into objects, respecting exclusions. + /// Elements without a subnet mask will be represented as with a single IP. /// /// Input string array to be parsed. /// Collection of . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. - public static bool TryParseSubnets(string[] values, out List result, bool negated = false) + public static bool TryParseToSubnets(string[] values, out List result, bool negated = false) { result = new List(); @@ -183,10 +184,14 @@ namespace MediaBrowser.Common.Net if (address != IPAddress.None && address != null) { - if (int.TryParse(v[1], out var netmask)) + if (v.Length > 1 && int.TryParse(v[1], out var netmask)) { result.Add(new IPNetwork(address, netmask)); } + else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress)) + { + result.Add(new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress))); + } else if (address.AddressFamily == AddressFamily.InterNetwork) { result.Add(new IPNetwork(address, 32)); @@ -207,15 +212,16 @@ namespace MediaBrowser.Common.Net } /// - /// Try parsing a string into a subnet, respecting exclusions. + /// Try parsing a string into an , respecting exclusions. + /// Inputs without a subnet mask will be represented as with a single IP. /// /// Input string to be parsed. /// An . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. - public static bool TryParseSubnet(string value, out IPNetwork? result, bool negated = false) + public static bool TryParseToSubnet(string value, out IPNetwork result, bool negated = false) { - result = null; + result = new IPNetwork(IPAddress.None, 32); if (string.IsNullOrEmpty(value)) { @@ -236,10 +242,14 @@ namespace MediaBrowser.Common.Net if (address != IPAddress.None && address != null) { - if (int.TryParse(v[1], out var netmask)) + if (v.Length > 1 && int.TryParse(v[1], out var netmask)) { result = new IPNetwork(address, netmask); } + else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress)) + { + result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + } else if (address.AddressFamily == AddressFamily.InterNetwork) { result = new IPNetwork(address, 32); @@ -250,7 +260,7 @@ namespace MediaBrowser.Common.Net } } - if (result != null) + if (!result.Prefix.Equals(IPAddress.None)) { return true; } diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index d492b6439..86b2ab21a 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -1,13 +1,11 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Net; using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; -using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; @@ -37,6 +35,8 @@ namespace Jellyfin.Networking.Tests [InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")] // eth16 only [InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")] + // eth16 only without mask + [InlineData("192.168.1.208,-16,eth16|200.200.200.200,11,eth11", "192.168.1.0/24", "[192.168.1.208/32]")] // All interfaces excluded. (including loopbacks) [InlineData("192.168.1.208/24,-16,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[]")] // vEthernet1 and vEthernet212 should be excluded. @@ -65,66 +65,79 @@ namespace Jellyfin.Networking.Tests /// IP Address. [Theory] [InlineData("127.0.0.1")] + [InlineData("127.0.0.1/8")] + [InlineData("192.168.1.2")] + [InlineData("192.168.1.2/24")] + [InlineData("192.168.1.2/255.255.255.0")] [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")] [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]")] [InlineData("fe80::7add:12ff:febb:c67b%16")] [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")] [InlineData("fe80::7add:12ff:febb:c67b%16:123")] [InlineData("[fe80::7add:12ff:febb:c67b%16]")] - [InlineData("192.168.1.2")] + [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")] public static void TryParseValidIPStringsTrue(string address) - => Assert.True(IPAddress.TryParse(address, out _)); + => Assert.True(NetworkExtensions.TryParseToSubnet(address, out _)); /// /// Checks invalid IP address formats. /// /// IP Address. [Theory] - [InlineData("192.168.1.2/255.255.255.0")] - [InlineData("192.168.1.2/24")] - [InlineData("127.0.0.1/8")] [InlineData("127.0.0.1#")] [InlineData("localhost!")] [InlineData("256.128.0.0.0.1")] - [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")] [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")] [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")] public static void TryParseInvalidIPStringsFalse(string address) - => Assert.False(IPAddress.TryParse(address, out _)); + => Assert.False(NetworkExtensions.TryParseToSubnet(address, out _)); + /// + /// Checks if IPv4 address is within a defined subnet. + /// + /// Network mask. + /// IP Address. [Theory] [InlineData("192.168.5.85/24", "192.168.5.1")] [InlineData("192.168.5.85/24", "192.168.5.254")] + [InlineData("192.168.5.85/255.255.255.0", "192.168.5.254")] [InlineData("10.128.240.50/30", "10.128.240.48")] [InlineData("10.128.240.50/30", "10.128.240.49")] [InlineData("10.128.240.50/30", "10.128.240.50")] [InlineData("10.128.240.50/30", "10.128.240.51")] + [InlineData("10.128.240.50/255.255.255.252", "10.128.240.51")] [InlineData("127.0.0.1/8", "127.0.0.1")] public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) { - var split = netMask.Split("/"); - var mask = int.Parse(split[1], CultureInfo.InvariantCulture); - var ipa = IPAddress.Parse(split[0]); - var ipn = new IPNetwork(ipa, mask); - Assert.True(ipn.Contains(IPAddress.Parse(ipAddress))); + var ipa = IPAddress.Parse(ipAddress); + Assert.True(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } + /// + /// Checks if IPv4 address is not within a defined subnet. + /// + /// Network mask. + /// IP Address. [Theory] [InlineData("192.168.5.85/24", "192.168.4.254")] [InlineData("192.168.5.85/24", "191.168.5.254")] + [InlineData("192.168.5.85/255.255.255.252", "192.168.4.254")] [InlineData("10.128.240.50/30", "10.128.240.47")] [InlineData("10.128.240.50/30", "10.128.240.52")] [InlineData("10.128.240.50/30", "10.128.239.50")] [InlineData("10.128.240.50/30", "10.127.240.51")] + [InlineData("10.128.240.50/255.255.255.252", "10.127.240.51")] public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) { - var split = netMask.Split("/"); - var mask = int.Parse(split[1], CultureInfo.InvariantCulture); - var ipa = IPAddress.Parse(split[0]); - var ipn = new IPNetwork(ipa, mask); - Assert.False(ipn.Contains(IPAddress.Parse(ipAddress))); + var ipa = IPAddress.Parse(ipAddress); + Assert.False(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } + /// + /// Checks if IPv6 address is within a defined subnet. + /// + /// Network mask. + /// IP Address. [Theory] [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")] [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFFF")] @@ -133,11 +146,7 @@ namespace Jellyfin.Networking.Tests [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")] public void IpV6SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) { - var split = netMask.Split("/"); - var mask = int.Parse(split[1], CultureInfo.InvariantCulture); - var ipa = IPAddress.Parse(split[0]); - var ipn = new IPNetwork(ipa, mask); - Assert.True(ipn.Contains(IPAddress.Parse(ipAddress))); + Assert.True(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } [Theory] @@ -148,11 +157,7 @@ namespace Jellyfin.Networking.Tests [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0001")] public void IpV6SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) { - var split = netMask.Split("/"); - var mask = int.Parse(split[1], CultureInfo.InvariantCulture); - var ipa = IPAddress.Parse(split[0]); - var ipn = new IPNetwork(ipa, mask); - Assert.False(ipn.Contains(IPAddress.Parse(ipAddress))); + Assert.False(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } [Theory] @@ -262,7 +267,7 @@ namespace Jellyfin.Networking.Tests if (nm.TryParseInterface(result, out List? resultObj) && resultObj != null) { - // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks). + // Parse out IPAddresses so we can do a string comparison (ignore subnet masks). result = resultObj.First().Address.ToString(); } -- cgit v1.2.3 From 3f6354cdb832560ec811f1766666dd9ca1f2a208 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 7 Dec 2022 17:41:32 +0100 Subject: Fix .NET 7 compatibility --- Emby.Server.Implementations/ApplicationHost.cs | 2 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 10 +++++----- tests/Jellyfin.Networking.Tests/NetworkParseTests.cs | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 4733b39ab..df4f3e676 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1094,7 +1094,7 @@ namespace Emby.Server.Implementations { int? requestPort = request.Host.Port; if (requestPort == null - || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) + || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase))) { requestPort = -1; diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index e37a5dc6b..97f0abbb5 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,10 +1,10 @@ -using Microsoft.AspNetCore.HttpOverrides; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; +using Microsoft.AspNetCore.HttpOverrides; namespace MediaBrowser.Common.Net { @@ -131,7 +131,7 @@ namespace MediaBrowser.Common.Net /// URI safe conversion of the address. public static string FormatIpString(IPAddress? address) { - if (address == null) + if (address is null) { return string.Empty; } @@ -163,7 +163,7 @@ namespace MediaBrowser.Common.Net { result = new List(); - if (values == null || values.Length == 0) + if (values is null || values.Length == 0) { return false; } @@ -182,7 +182,7 @@ namespace MediaBrowser.Common.Net _ = IPAddress.TryParse(v[0][0..], out address); } - if (address != IPAddress.None && address != null) + if (address != IPAddress.None && address is not null) { if (v.Length > 1 && int.TryParse(v[1], out var netmask)) { @@ -240,7 +240,7 @@ namespace MediaBrowser.Common.Net _ = IPAddress.TryParse(v[0][0..], out address); } - if (address != IPAddress.None && address != null) + if (address != IPAddress.None && address is not null) { if (v.Length > 1 && int.TryParse(v[1], out var netmask)) { diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 86b2ab21a..241d2314b 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -207,7 +207,7 @@ namespace Jellyfin.Networking.Tests // Check to see if dns resolution is working. If not, skip test. _ = NetworkExtensions.TryParseHost(source, out var host); - if (resultObj != null && host.Length > 0) + if (resultObj is not null && host.Length > 0) { result = resultObj.First().Address.ToString(); var intf = nm.GetBindInterface(source, out _); @@ -265,7 +265,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - if (nm.TryParseInterface(result, out List? resultObj) && resultObj != null) + if (nm.TryParseInterface(result, out List? resultObj) && resultObj is not null) { // Parse out IPAddresses so we can do a string comparison (ignore subnet masks). result = resultObj.First().Address.ToString(); -- cgit v1.2.3 From 4eba16c6726564b159e395e188ec89f69d990e52 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 15 Feb 2023 22:34:44 +0100 Subject: Apply review suggestions --- .../EntryPoints/UdpServerEntryPoint.cs | 5 +- .../Configuration/NetworkConfiguration.cs | 4 +- .../NetworkConfigurationExtensions.cs | 2 +- Jellyfin.Networking/Manager/NetworkManager.cs | 101 ++++++++++++--------- .../Extensions/ApiServiceCollectionExtensions.cs | 2 +- MediaBrowser.Common/Net/INetworkManager.cs | 6 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 67 ++++++-------- .../NetworkManagerTests.cs | 8 +- .../Jellyfin.Networking.Tests/NetworkParseTests.cs | 32 +++---- tests/Jellyfin.Server.Tests/ParseNetworkTests.cs | 8 +- 10 files changed, 117 insertions(+), 118 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index c2ffaf1bd..b5a33a735 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -102,7 +102,10 @@ namespace Emby.Server.Implementations.EntryPoints _udpServers.Add(new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Any, PortNumber)); } - _udpServers.ForEach(u => u.Start(_cancellationTokenSource.Token)); + foreach (var server in _udpServers) + { + server.Start(_cancellationTokenSource.Token); + } } catch (SocketException ex) { diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index f90419851..f31d2bce2 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -115,12 +115,12 @@ namespace Jellyfin.Networking.Configuration /// /// Gets or sets a value indicating whether IPv6 is enabled or not. /// - public bool EnableIPV4 { get; set; } = true; + public bool EnableIPv4 { get; set; } = true; /// /// Gets or sets a value indicating whether IPv6 is enabled or not. /// - public bool EnableIPV6 { get; set; } + public bool EnableIPv6 { get; set; } /// /// Gets or sets a value indicating whether access outside of the LAN is permitted. 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 /// The . public static NetworkConfiguration GetNetworkConfiguration(this IConfigurationManager config) { - return config.GetConfiguration("network"); + return config.GetConfiguration(NetworkConfigurationStore.StoreKey); } } } diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index ca9e9274f..5f82950fc 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -111,12 +111,12 @@ namespace Jellyfin.Networking.Manager /// /// Gets a value indicating whether IP4 is enabled. /// - public bool IsIpv4Enabled => _configurationManager.GetNetworkConfiguration().EnableIPV4; + public bool IsIPv4Enabled => _configurationManager.GetNetworkConfiguration().EnableIPv4; /// /// Gets a value indicating whether IP6 is enabled. /// - public bool IsIpv6Enabled => _configurationManager.GetNetworkConfiguration().EnableIPV6; + public bool IsIPv6Enabled => _configurationManager.GetNetworkConfiguration().EnableIPv6; /// /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. @@ -229,7 +229,7 @@ namespace Jellyfin.Networking.Manager // Populate interface list foreach (var info in ipProperties.UnicastAddresses) { - if (IsIpv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) + 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; @@ -237,7 +237,7 @@ namespace Jellyfin.Networking.Manager _interfaces.Add(interfaceObject); } - else if (IsIpv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) + 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; @@ -268,12 +268,12 @@ namespace Jellyfin.Networking.Manager { _logger.LogWarning("No interface information available. Using loopback interface(s)."); - if (IsIpv4Enabled && !IsIpv6Enabled) + if (IsIPv4Enabled && !IsIPv6Enabled) { _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); } - if (!IsIpv4Enabled && IsIpv6Enabled) + if (!IsIPv4Enabled && IsIPv6Enabled) { _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } @@ -311,14 +311,14 @@ namespace Jellyfin.Networking.Manager { _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); - if (IsIpv6Enabled) + if (IsIPv6Enabled) { _lanSubnets.Add(new IPNetwork(IPAddress.IPv6Loopback, 128)); // RFC 4291 (Loopback) _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // RFC 4291 (Site local) _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // RFC 4193 (Unique local) } - if (IsIpv4Enabled) + if (IsIPv4Enabled) { _lanSubnets.Add(new IPNetwork(IPAddress.Loopback, 8)); // RFC 5735 (Loopback) _lanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); // RFC 1918 (private) @@ -382,13 +382,13 @@ namespace Jellyfin.Networking.Manager } // Remove all IPv4 interfaces if IPv4 is disabled - if (!IsIpv4Enabled) + if (!IsIPv4Enabled) { _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork); } // Remove all IPv6 interfaces if IPv6 is disabled - if (!IsIpv6Enabled) + if (!IsIPv6Enabled) { _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); } @@ -470,7 +470,7 @@ namespace Jellyfin.Networking.Manager _publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement; } } - else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result != null) + else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result is not null) { var data = new IPData(result.Prefix, result); _publishedServerUrls[data] = replacement; @@ -492,7 +492,7 @@ namespace Jellyfin.Networking.Manager private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) { - if (evt.Key.Equals("network", StringComparison.Ordinal)) + if (evt.Key.Equals(NetworkConfigurationStore.StoreKey, StringComparison.Ordinal)) { UpdateSettings((NetworkConfiguration)evt.NewConfiguration); } @@ -581,8 +581,8 @@ namespace Jellyfin.Networking.Manager // Use interface IP instead of name foreach (var iface in matchedInterfaces) { - if ((IsIpv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) - || (IsIpv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) + if ((IsIPv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIPv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) { result.Add(iface); } @@ -634,18 +634,18 @@ namespace Jellyfin.Networking.Manager /// public IReadOnlyList GetLoopbacks() { - if (!(IsIpv4Enabled && IsIpv4Enabled)) + if (!(IsIPv4Enabled && IsIPv4Enabled)) { return Array.Empty(); } var loopbackNetworks = new List(); - if (IsIpv4Enabled) + if (IsIPv4Enabled) { loopbackNetworks.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); } - if (IsIpv6Enabled) + if (IsIPv6Enabled) { loopbackNetworks.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } @@ -674,16 +674,16 @@ namespace Jellyfin.Networking.Manager return result; } - if (IsIpv4Enabled && IsIpv6Enabled) + if (IsIPv4Enabled && IsIPv6Enabled) { // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any by default result.Add(new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))); } - else if (IsIpv4Enabled) + else if (IsIPv4Enabled) { result.Add(new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))); } - else if (IsIpv6Enabled) + else if (IsIPv6Enabled) { // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too. foreach (var iface in _interfaces) @@ -701,7 +701,7 @@ namespace Jellyfin.Networking.Manager /// public string GetBindInterface(string source, out int? port) { - if (!NetworkExtensions.TryParseHost(source, out var addresses, IsIpv4Enabled, IsIpv6Enabled)) + if (!NetworkExtensions.TryParseHost(source, out var addresses, IsIPv4Enabled, IsIPv6Enabled)) { addresses = Array.Empty(); } @@ -726,14 +726,14 @@ namespace Jellyfin.Networking.Manager string result; - if (source != null) + if (source is not null) { - if (IsIpv4Enabled && !IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) + if (IsIPv4Enabled && !IsIPv6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) { _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); } - if (!IsIpv4Enabled && IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) + if (!IsIPv4Enabled && IsIPv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) { _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); } @@ -759,6 +759,7 @@ namespace Jellyfin.Networking.Manager } // 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) @@ -766,6 +767,7 @@ namespace Jellyfin.Networking.Manager if (availableInterfaces.Count > 0) { + // If no source address is given, use the preferred (first) interface if (source is null) { result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address); @@ -773,16 +775,6 @@ namespace Jellyfin.Networking.Manager return result; } - foreach (var intf in availableInterfaces) - { - if (intf.Address.Equals(source)) - { - result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: Found matching interface to use as bind address: {Result}", source, result); - return result; - } - } - // 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) @@ -790,14 +782,19 @@ namespace Jellyfin.Networking.Manager if (intf.Subnet.Contains(source)) { result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: Found internal interface with matching subnet, using it as bind address: {Result}", source, result); + _logger.LogDebug("{Source}: Found interface with matching subnet, using it as bind address: {Result}", source, result); return result; } } + + // 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; } // There isn't any others, so we'll use the loopback. - result = IsIpv4Enabled && !IsIpv6Enabled ? "127.0.0.1" : "::1"; + result = IsIPv4Enabled && !IsIPv6Enabled ? "127.0.0.1" : "::1"; _logger.LogWarning("{Source}: Only loopback {Result} returned, using that as bind address.", source, result); return result; } @@ -819,12 +816,12 @@ namespace Jellyfin.Networking.Manager return IPAddress.IsLoopback(subnet.Prefix) || (_lanSubnets.Any(x => x.Contains(subnet.Prefix)) && !_excludedSubnets.Any(x => x.Contains(subnet.Prefix))); } - if (NetworkExtensions.TryParseHost(address, out var addresses, IsIpv4Enabled, IsIpv6Enabled)) + if (NetworkExtensions.TryParseHost(address, out var addresses, IsIPv4Enabled, IsIPv6Enabled)) { bool match = false; foreach (var ept in addresses) { - match |= IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept))); + match = match || IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept))); if (match) { @@ -860,15 +857,29 @@ namespace Jellyfin.Networking.Manager bool match = false; foreach (var lanSubnet in _lanSubnets) { - match |= lanSubnet.Contains(address); + match = lanSubnet.Contains(address); + + if (match) + { + break; + } + } + + if (!match) + { + return match; } foreach (var excludedSubnet in _excludedSubnets) { - match &= !excludedSubnet.Contains(address); + match = match && !excludedSubnet.Contains(address); + + if (!match) + { + break; + } } - NetworkExtensions.IsIPv6LinkLocal(address); return match; } @@ -905,7 +916,7 @@ namespace Jellyfin.Networking.Manager // Get address interface. var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(x => data.Key.Subnet.Contains(x.Address)); - if (intf?.Address != null) + if (intf?.Address is not null) { // Match IP address. bindPreference = data.Value; @@ -930,7 +941,7 @@ namespace Jellyfin.Networking.Manager } } - if (port != null) + if (port is not null) { _logger.LogDebug("{Source}: Matching bind address override found: {Address}:{Port}", source, bindPreference, port); } @@ -981,7 +992,7 @@ namespace Jellyfin.Networking.Manager .Select(x => x.Address) .FirstOrDefault(); - if (bindAddress != null) + if (bindAddress is not null) { result = NetworkExtensions.FormatIpString(bindAddress); _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result); @@ -1001,7 +1012,7 @@ namespace Jellyfin.Networking.Manager .Select(x => x.Address) .FirstOrDefault(); - if (bindAddress != null) + if (bindAddress is not null) { result = NetworkExtensions.FormatIpString(bindAddress); _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result); diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 5065fbdbb..71f23b788 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -367,7 +367,7 @@ namespace Jellyfin.Server.Extensions private static void AddIpAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength) { - if ((!config.EnableIPV4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPV6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) + if ((!config.EnableIPv4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPv6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) { return; } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index f0f16af78..5721b19ca 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -19,12 +19,12 @@ namespace MediaBrowser.Common.Net /// /// Gets a value indicating whether IPv4 is enabled. /// - bool IsIpv4Enabled { get; } + bool IsIPv4Enabled { get; } /// /// Gets a value indicating whether IPv6 is enabled. /// - bool IsIpv6Enabled { get; } + bool IsIPv6Enabled { get; } /// /// Calculates the list of interfaces to use for Kestrel. @@ -119,7 +119,7 @@ namespace MediaBrowser.Common.Net /// Interface name. /// Resulting object's IP addresses, if successful. /// Success of the operation. - bool TryParseInterface(string intf, out List? result); + bool TryParseInterface(string intf, out List result); /// /// Returns all internal (LAN) bind interface addresses. diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 97f0abbb5..7c36081e6 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; @@ -170,36 +171,9 @@ namespace MediaBrowser.Common.Net for (int a = 0; a < values.Length; a++) { - string[] v = values[a].Trim().Split("/"); - - var address = IPAddress.None; - if (negated && v[0].StartsWith('!')) - { - _ = IPAddress.TryParse(v[0][1..], out address); - } - else if (!negated) + if (TryParseToSubnet(values[a], out var innerResult, negated)) { - _ = IPAddress.TryParse(v[0][0..], out address); - } - - if (address != IPAddress.None && address is not null) - { - if (v.Length > 1 && int.TryParse(v[1], out var netmask)) - { - result.Add(new IPNetwork(address, netmask)); - } - else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress)) - { - result.Add(new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress))); - } - else if (address.AddressFamily == AddressFamily.InterNetwork) - { - result.Add(new IPNetwork(address, 32)); - } - else if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - result.Add(new IPNetwork(address, 128)); - } + result.Add(innerResult); } } @@ -228,27 +202,32 @@ namespace MediaBrowser.Common.Net return false; } - string[] v = value.Trim().Split("/"); + var splitString = value.Trim().Split("/"); + var ipBlock = splitString[0]; var address = IPAddress.None; - if (negated && v[0].StartsWith('!')) + if (negated && ipBlock.StartsWith('!') && IPAddress.TryParse(ipBlock[1..], out var tmpAddress)) { - _ = IPAddress.TryParse(v[0][1..], out address); + address = tmpAddress; } - else if (!negated) + else if (!negated && IPAddress.TryParse(ipBlock, out tmpAddress)) { - _ = IPAddress.TryParse(v[0][0..], out address); + address = tmpAddress; } if (address != IPAddress.None && address is not null) { - if (v.Length > 1 && int.TryParse(v[1], out var netmask)) - { - result = new IPNetwork(address, netmask); - } - else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress)) + if (splitString.Length > 1) { - result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + var subnetBlock = splitString[1]; + if (int.TryParse(subnetBlock, out var netmask)) + { + result = new IPNetwork(address, netmask); + } + else if (IPAddress.TryParse(subnetBlock, out var netmaskAddress)) + { + result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + } } else if (address.AddressFamily == AddressFamily.InterNetwork) { @@ -353,7 +332,13 @@ namespace MediaBrowser.Common.Net /// The broadcast address. public static IPAddress GetBroadcastAddress(IPNetwork network) { - uint ipAddress = BitConverter.ToUInt32(network.Prefix.GetAddressBytes(), 0); + var addressBytes = network.Prefix.GetAddressBytes(); + if (BitConverter.IsLittleEndian) + { + addressBytes.Reverse(); + } + + uint ipAddress = BitConverter.ToUInt32(addressBytes, 0); uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0); uint broadCastIpAddress = ipAddress | ~ipMaskV4; diff --git a/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs index 61f913252..85226d430 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs @@ -23,8 +23,8 @@ namespace Jellyfin.Networking.Tests var ip = IPAddress.Parse(value); var conf = new NetworkConfiguration() { - EnableIPV6 = true, - EnableIPV4 = true, + EnableIPv6 = true, + EnableIPv4 = true, LocalNetworkSubnets = network.Split(',') }; @@ -50,8 +50,8 @@ namespace Jellyfin.Networking.Tests var ip = IPAddress.Parse(value); var conf = new NetworkConfiguration() { - EnableIPV6 = true, - EnableIPV4 = true, + EnableIPv6 = true, + EnableIPv4 = true, LocalNetworkSubnets = network.Split(',') }; diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 241d2314b..c493ce5ea 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -47,8 +47,8 @@ namespace Jellyfin.Networking.Tests { var conf = new NetworkConfiguration() { - EnableIPV6 = true, - EnableIPV4 = true, + EnableIPv6 = true, + EnableIPv4 = true, LocalNetworkSubnets = lan?.Split(';') ?? throw new ArgumentNullException(nameof(lan)) }; @@ -107,7 +107,7 @@ namespace Jellyfin.Networking.Tests [InlineData("10.128.240.50/30", "10.128.240.51")] [InlineData("10.128.240.50/255.255.255.252", "10.128.240.51")] [InlineData("127.0.0.1/8", "127.0.0.1")] - public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) + public void IPv4SubnetMaskMatchesValidIPAddress(string netMask, string ipAddress) { var ipa = IPAddress.Parse(ipAddress); Assert.True(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); @@ -127,7 +127,7 @@ namespace Jellyfin.Networking.Tests [InlineData("10.128.240.50/30", "10.128.239.50")] [InlineData("10.128.240.50/30", "10.127.240.51")] [InlineData("10.128.240.50/255.255.255.252", "10.127.240.51")] - public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) + public void IPv4SubnetMaskDoesNotMatchInvalidIPAddress(string netMask, string ipAddress) { var ipa = IPAddress.Parse(ipAddress); Assert.False(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); @@ -144,7 +144,7 @@ namespace Jellyfin.Networking.Tests [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0001:0000:0000:0000")] [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFF0")] [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")] - public void IpV6SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) + public void IPv6SubnetMaskMatchesValidIPAddress(string netMask, string ipAddress) { Assert.True(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } @@ -155,7 +155,7 @@ namespace Jellyfin.Networking.Tests [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0001:0000:0000:0000")] [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFF0")] [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0001")] - public void IpV6SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) + public void IPv6SubnetMaskDoesNotMatchInvalidIPAddress(string netMask, string ipAddress) { Assert.False(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress))); } @@ -194,8 +194,8 @@ namespace Jellyfin.Networking.Tests var conf = new NetworkConfiguration() { LocalNetworkAddresses = bindAddresses.Split(','), - EnableIPV6 = ipv6enabled, - EnableIPV4 = true + EnableIPv6 = ipv6enabled, + EnableIPv4 = true }; NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11"; @@ -256,8 +256,8 @@ namespace Jellyfin.Networking.Tests { LocalNetworkSubnets = lan.Split(','), LocalNetworkAddresses = bindAddresses.Split(','), - EnableIPV6 = ipv6enabled, - EnableIPV4 = true, + EnableIPv6 = ipv6enabled, + EnableIPv4 = true, PublishedServerUriBySubnet = new string[] { publishedServers } }; @@ -281,13 +281,13 @@ namespace Jellyfin.Networking.Tests [InlineData("185.10.10.10", "185.10.10.10", false)] [InlineData("", "100.100.100.100", false)] - public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIpsInWhitelist(string addresses, string remoteIp, bool denied) + public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIPsInWhitelist(string addresses, string remoteIp, bool denied) { // 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. var conf = new NetworkConfiguration() { - EnableIPV4 = true, + EnableIPv4 = true, RemoteIPFilter = addresses.Split(','), IsRemoteIPFilterBlacklist = false }; @@ -301,13 +301,13 @@ namespace Jellyfin.Networking.Tests [InlineData("185.10.10.10", "185.10.10.10", true)] [InlineData("", "100.100.100.100", false)] - public void HasRemoteAccess_GivenBlacklist_BlacklistTheIps(string addresses, string remoteIp, bool denied) + public void HasRemoteAccess_GivenBlacklist_BlacklistTheIPs(string addresses, string remoteIp, bool denied) { // 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. var conf = new NetworkConfiguration() { - EnableIPV4 = true, + EnableIPv4 = true, RemoteIPFilter = addresses.Split(','), IsRemoteIPFilterBlacklist = true }; @@ -326,7 +326,7 @@ namespace Jellyfin.Networking.Tests { var conf = new NetworkConfiguration { - EnableIPV4 = true, + EnableIPv4 = true, LocalNetworkSubnets = lan.Split(','), LocalNetworkAddresses = bind.Split(',') }; @@ -350,7 +350,7 @@ namespace Jellyfin.Networking.Tests { var conf = new NetworkConfiguration { - EnableIPV4 = true, + EnableIPv4 = true, LocalNetworkSubnets = lan.Split(','), LocalNetworkAddresses = bind.Split(',') }; diff --git a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs index 12a9beb9e..49516cccc 100644 --- a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs +++ b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs @@ -77,8 +77,8 @@ namespace Jellyfin.Server.Tests var settings = new NetworkConfiguration { - EnableIPV4 = ip4, - EnableIPV6 = ip6 + EnableIPv4 = ip4, + EnableIPv6 = ip6 }; ForwardedHeadersOptions options = new ForwardedHeadersOptions(); @@ -116,8 +116,8 @@ namespace Jellyfin.Server.Tests { var conf = new NetworkConfiguration() { - EnableIPV6 = true, - EnableIPV4 = true, + EnableIPv6 = true, + EnableIPv4 = true, }; return new NetworkManager(GetMockConfig(conf), new NullLogger()); -- cgit v1.2.3 From 20fd05b05081ad387e94128b4f26d907808c8f0c Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Fri, 17 Feb 2023 19:27:36 +0100 Subject: Consistently write IP in upercase --- Emby.Dlna/PlayTo/PlayToManager.cs | 2 +- Emby.Dlna/Ssdp/DeviceDiscovery.cs | 2 +- .../HttpServer/WebSocketManager.cs | 2 +- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 4 +- .../TunerHosts/HdHomerun/HdHomerunManager.cs | 10 ++--- .../AnonymousLanAccessHandler.cs | 2 +- .../DefaultAuthorizationHandler.cs | 2 +- .../LocalAccessOrRequiresElevationHandler.cs | 2 +- Jellyfin.Api/Controllers/MediaInfoController.cs | 2 +- Jellyfin.Api/Controllers/SystemController.cs | 2 +- .../Controllers/UniversalAudioController.cs | 2 +- Jellyfin.Api/Controllers/UserController.cs | 18 ++++----- Jellyfin.Api/Helpers/DynamicHlsHelper.cs | 2 +- Jellyfin.Api/Helpers/MediaInfoHelper.cs | 4 +- Jellyfin.Api/Helpers/RequestHelpers.cs | 2 +- .../IpBasedAccessValidationMiddleware.cs | 10 ++--- Jellyfin.Api/Middleware/LanFilteringMiddleware.cs | 2 +- Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs | 4 +- Jellyfin.Networking/Manager/NetworkManager.cs | 26 ++++++------- .../Extensions/ApiApplicationBuilderExtensions.cs | 4 +- .../Extensions/ApiServiceCollectionExtensions.cs | 8 ++-- Jellyfin.Server/Startup.cs | 2 +- .../Extensions/HttpContextExtensions.cs | 2 +- MediaBrowser.Common/Net/INetworkManager.cs | 6 +-- MediaBrowser.Common/Net/NetworkExtensions.cs | 20 +++++----- MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs | 4 +- RSSDP/DeviceAvailableEventArgs.cs | 2 +- RSSDP/ISsdpCommunicationsServer.cs | 6 +-- RSSDP/RequestReceivedEventArgs.cs | 6 +-- RSSDP/ResponseReceivedEventArgs.cs | 2 +- RSSDP/SsdpCommunicationsServer.cs | 44 +++++++++++----------- RSSDP/SsdpDeviceLocator.cs | 26 ++++++------- RSSDP/SsdpDevicePublisher.cs | 22 +++++------ .../Jellyfin.Networking.Tests/NetworkParseTests.cs | 10 ++--- 34 files changed, 132 insertions(+), 132 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs index f4a9a90af..b9bfad9d9 100644 --- a/Emby.Dlna/PlayTo/PlayToManager.cs +++ b/Emby.Dlna/PlayTo/PlayToManager.cs @@ -189,7 +189,7 @@ namespace Emby.Dlna.PlayTo _sessionManager.UpdateDeviceName(sessionInfo.Id, deviceName); - string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIpAddress); + string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIPAddress); controller = new PlayToController( sessionInfo, diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index 43d673c77..4fbbc3885 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -110,7 +110,7 @@ namespace Emby.Dlna.Ssdp { Location = e.DiscoveredDevice.DescriptionLocation, Headers = headers, - RemoteIpAddress = e.RemoteIpAddress + RemoteIPAddress = e.RemoteIPAddress }); DeviceDiscoveredInternal?.Invoke(this, args); diff --git a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs index 4f7d1c40a..ecfb242f6 100644 --- a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs +++ b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs @@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.HttpServer using var connection = new WebSocketConnection( _loggerFactory.CreateLogger(), webSocket, - context.GetNormalizedRemoteIp()) + context.GetNormalizedRemoteIP()) { OnReceive = ProcessWebSocketMessageReceived }; diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index e76961ce9..a86c329d6 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -667,12 +667,12 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun while (!cancellationToken.IsCancellationRequested) { var response = await udpClient.ReceiveMessageFromAsync(receiveBuffer, new IPEndPoint(IPAddress.Any, 0), cancellationToken).ConfigureAwait(false); - var deviceIp = ((IPEndPoint)response.RemoteEndPoint).Address.ToString(); + var deviceIP = ((IPEndPoint)response.RemoteEndPoint).Address.ToString(); // Check to make sure we have enough bytes received to be a valid message and make sure the 2nd byte is the discover reply byte if (response.ReceivedBytes > 13 && receiveBuffer[1] == 3) { - var deviceAddress = "http://" + deviceIp; + var deviceAddress = "http://" + deviceIP; var info = await TryGetTunerHostInfo(deviceAddress, cancellationToken).ConfigureAwait(false); diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs index 81eb083f6..ae7df22f8 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs @@ -48,10 +48,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun GC.SuppressFinalize(this); } - public async Task CheckTunerAvailability(IPAddress remoteIp, int tuner, CancellationToken cancellationToken) + public async Task CheckTunerAvailability(IPAddress remoteIP, int tuner, CancellationToken cancellationToken) { using var client = new TcpClient(); - await client.ConnectAsync(remoteIp, HdHomeRunPort).ConfigureAwait(false); + await client.ConnectAsync(remoteIP, HdHomeRunPort).ConfigureAwait(false); using var stream = client.GetStream(); return await CheckTunerAvailability(stream, tuner, cancellationToken).ConfigureAwait(false); @@ -75,9 +75,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } } - public async Task StartStreaming(IPAddress remoteIp, IPAddress localIp, int localPort, IHdHomerunChannelCommands commands, int numTuners, CancellationToken cancellationToken) + public async Task StartStreaming(IPAddress remoteIP, IPAddress localIP, int localPort, IHdHomerunChannelCommands commands, int numTuners, CancellationToken cancellationToken) { - _remoteEndPoint = new IPEndPoint(remoteIp, HdHomeRunPort); + _remoteEndPoint = new IPEndPoint(remoteIP, HdHomeRunPort); _tcpClient = new TcpClient(); await _tcpClient.ConnectAsync(_remoteEndPoint, cancellationToken).ConfigureAwait(false); @@ -125,7 +125,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun } } - var targetValue = string.Format(CultureInfo.InvariantCulture, "rtp://{0}:{1}", localIp, localPort); + var targetValue = string.Format(CultureInfo.InvariantCulture, "rtp://{0}:{1}", localIP, localPort); var targetMsgLen = WriteSetMessage(buffer, i, "target", targetValue, lockKeyValue); await stream.WriteAsync(buffer.AsMemory(0, targetMsgLen), cancellationToken).ConfigureAwait(false); diff --git a/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs b/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs index 741b88ea9..3c1401ded 100644 --- a/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs +++ b/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs @@ -30,7 +30,7 @@ namespace Jellyfin.Api.Auth.AnonymousLanAccessPolicy /// protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AnonymousLanAccessRequirement requirement) { - var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIp(); + var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIP(); // Loopback will be on LAN, so we can accept null. if (ip is null || _networkManager.IsInLocalNetwork(ip)) diff --git a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs index b1d97e4a1..c0db4d1fc 100644 --- a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs +++ b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs @@ -47,7 +47,7 @@ namespace Jellyfin.Api.Auth.DefaultAuthorizationPolicy } var isInLocalNetwork = _httpContextAccessor.HttpContext is not null - && _networkManager.IsInLocalNetwork(_httpContextAccessor.HttpContext.GetNormalizedRemoteIp()); + && _networkManager.IsInLocalNetwork(_httpContextAccessor.HttpContext.GetNormalizedRemoteIP()); var user = _userManager.GetUserById(userId); if (user is null) { diff --git a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs index 6ed6fc90b..557b7d3aa 100644 --- a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs +++ b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs @@ -31,7 +31,7 @@ namespace Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy /// protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, LocalAccessOrRequiresElevationRequirement requirement) { - var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIp(); + var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIP(); // Loopback will be on LAN, so we can accept null. if (ip is null || _networkManager.IsInLocalNetwork(ip)) diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs index ea10dd771..1bef35c27 100644 --- a/Jellyfin.Api/Controllers/MediaInfoController.cs +++ b/Jellyfin.Api/Controllers/MediaInfoController.cs @@ -183,7 +183,7 @@ public class MediaInfoController : BaseJellyfinApiController enableTranscoding.Value, allowVideoStreamCopy.Value, allowAudioStreamCopy.Value, - Request.HttpContext.GetNormalizedRemoteIp()); + Request.HttpContext.GetNormalizedRemoteIP()); } _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate); diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs index 4ab705f40..91901518f 100644 --- a/Jellyfin.Api/Controllers/SystemController.cs +++ b/Jellyfin.Api/Controllers/SystemController.cs @@ -179,7 +179,7 @@ public class SystemController : BaseJellyfinApiController return new EndPointInfo { IsLocal = HttpContext.IsLocal(), - IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp()) + IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIP()) }; } diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs index 345521597..04f2109ea 100644 --- a/Jellyfin.Api/Controllers/UniversalAudioController.cs +++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs @@ -143,7 +143,7 @@ public class UniversalAudioController : BaseJellyfinApiController true, true, true, - Request.HttpContext.GetNormalizedRemoteIp()); + Request.HttpContext.GetNormalizedRemoteIP()); } _mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate); diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs index b0973b8a1..ec5425578 100644 --- a/Jellyfin.Api/Controllers/UserController.cs +++ b/Jellyfin.Api/Controllers/UserController.cs @@ -129,7 +129,7 @@ public class UserController : BaseJellyfinApiController return NotFound("User not found"); } - var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIp().ToString()); + var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIP().ToString()); return result; } @@ -211,7 +211,7 @@ public class UserController : BaseJellyfinApiController DeviceId = auth.DeviceId, DeviceName = auth.Device, Password = request.Pw, - RemoteEndPoint = HttpContext.GetNormalizedRemoteIp().ToString(), + RemoteEndPoint = HttpContext.GetNormalizedRemoteIP().ToString(), Username = request.Username }).ConfigureAwait(false); @@ -220,7 +220,7 @@ public class UserController : BaseJellyfinApiController catch (SecurityException e) { // rethrow adding IP address to message - throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e); + throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIP()}] {e.Message}", e); } } @@ -242,7 +242,7 @@ public class UserController : BaseJellyfinApiController catch (SecurityException e) { // rethrow adding IP address to message - throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e); + throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIP()}] {e.Message}", e); } } @@ -288,7 +288,7 @@ public class UserController : BaseJellyfinApiController user.Username, request.CurrentPw ?? string.Empty, request.CurrentPw ?? string.Empty, - HttpContext.GetNormalizedRemoteIp().ToString(), + HttpContext.GetNormalizedRemoteIP().ToString(), false).ConfigureAwait(false); if (success is null) @@ -489,7 +489,7 @@ public class UserController : BaseJellyfinApiController await _userManager.ChangePassword(newUser, request.Password).ConfigureAwait(false); } - var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIp().ToString()); + var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIP().ToString()); return result; } @@ -504,7 +504,7 @@ public class UserController : BaseJellyfinApiController [ProducesResponseType(StatusCodes.Status200OK)] public async Task> ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest) { - var ip = HttpContext.GetNormalizedRemoteIp(); + var ip = HttpContext.GetNormalizedRemoteIP(); var isLocal = HttpContext.IsLocal() || _networkManager.IsInLocalNetwork(ip); @@ -585,7 +585,7 @@ public class UserController : BaseJellyfinApiController if (filterByNetwork) { - if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp())) + if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIP())) { users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess)); } @@ -593,7 +593,7 @@ public class UserController : BaseJellyfinApiController var result = users .OrderBy(u => u.Username) - .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIp().ToString())); + .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIP().ToString())); return result; } diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index 245239233..f9ca39209 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -273,7 +273,7 @@ public class DynamicHlsHelper } } - if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.GetNormalizedRemoteIp())) + if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.GetNormalizedRemoteIP())) { var requestedVideoBitrate = state.VideoRequest is null ? 0 : state.VideoRequest.VideoBitRate ?? 0; diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs index 5910d8073..a36028cfe 100644 --- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs +++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs @@ -421,7 +421,7 @@ public class MediaInfoHelper true, true, true, - httpContext.GetNormalizedRemoteIp()); + httpContext.GetNormalizedRemoteIP()); } else { @@ -487,7 +487,7 @@ public class MediaInfoHelper { var isInLocalNetwork = _networkManager.IsInLocalNetwork(ipAddress); - _logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, ipAddress, isInLocalNetwork); + _logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIP: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, ipAddress, isInLocalNetwork); if (!isInLocalNetwork) { maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate); diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs index 0b7a4fa1a..1ab55bc31 100644 --- a/Jellyfin.Api/Helpers/RequestHelpers.cs +++ b/Jellyfin.Api/Helpers/RequestHelpers.cs @@ -98,7 +98,7 @@ public static class RequestHelpers httpContext.User.GetVersion(), httpContext.User.GetDeviceId(), httpContext.User.GetDevice(), - httpContext.GetNormalizedRemoteIp().ToString(), + httpContext.GetNormalizedRemoteIP().ToString(), user).ConfigureAwait(false); if (session is null) diff --git a/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs index f45b6b5c0..27bcd5570 100644 --- a/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs +++ b/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs @@ -9,15 +9,15 @@ namespace Jellyfin.Api.Middleware; /// /// Validates the IP of requests coming from local networks wrt. remote access. /// -public class IpBasedAccessValidationMiddleware +public class IPBasedAccessValidationMiddleware { private readonly RequestDelegate _next; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The next delegate in the pipeline. - public IpBasedAccessValidationMiddleware(RequestDelegate next) + public IPBasedAccessValidationMiddleware(RequestDelegate next) { _next = next; } @@ -37,9 +37,9 @@ public class IpBasedAccessValidationMiddleware return; } - var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback; + var remoteIP = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback; - if (!networkManager.HasRemoteAccess(remoteIp)) + if (!networkManager.HasRemoteAccess(remoteIP)) { return; } diff --git a/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs index 9c2194faf..94de30d1b 100644 --- a/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs +++ b/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs @@ -38,7 +38,7 @@ public class LanFilteringMiddleware return; } - var host = httpContext.GetNormalizedRemoteIp(); + var host = httpContext.GetNormalizedRemoteIP(); if (!networkManager.IsInLocalNetwork(host)) { return; diff --git a/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs b/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs index db3917743..279ea70d8 100644 --- a/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs +++ b/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs @@ -51,9 +51,9 @@ public class ResponseTimeMiddleware if (enableWarning && responseTimeMs > warningThreshold && _logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug( - "Slow HTTP Response from {Url} to {RemoteIp} in {Elapsed:g} with Status Code {StatusCode}", + "Slow HTTP Response from {Url} to {RemoteIP} in {Elapsed:g} with Status Code {StatusCode}", context.Request.GetDisplayUrl(), - context.GetNormalizedRemoteIp(), + context.GetNormalizedRemoteIP(), responseTime, context.Response.StatusCode); } diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index cdd34bc89..dd90a5b51 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -122,7 +122,7 @@ namespace Jellyfin.Networking.Manager /// /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. /// - public bool TrustAllIpv6Interfaces { get; private set; } + public bool TrustAllIPv6Interfaces { get; private set; } /// /// Gets the Published server override list. @@ -596,17 +596,17 @@ namespace Jellyfin.Networking.Manager } /// - public bool HasRemoteAccess(IPAddress remoteIp) + public bool HasRemoteAccess(IPAddress remoteIP) { 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.Any() && !_lanSubnets.Any(x => x.Contains(remoteIp))) + if (_remoteAddressFilter.Any() && !_lanSubnets.Any(x => x.Contains(remoteIP))) { // remoteAddressFilter is a whitelist or blacklist. - var matches = _remoteAddressFilter.Count(remoteNetwork => remoteNetwork.Contains(remoteIp)); + var matches = _remoteAddressFilter.Count(remoteNetwork => remoteNetwork.Contains(remoteIP)); if ((!config.IsRemoteIPFilterBlacklist && matches > 0) || (config.IsRemoteIPFilterBlacklist && matches == 0)) { @@ -616,7 +616,7 @@ namespace Jellyfin.Networking.Manager return false; } } - else if (!_lanSubnets.Any(x => x.Contains(remoteIp))) + else if (!_lanSubnets.Any(x => x.Contains(remoteIP))) { // Remote not enabled. So everyone should be LAN. return false; @@ -771,7 +771,7 @@ namespace Jellyfin.Networking.Manager // If no source address is given, use the preferred (first) interface if (source is null) { - result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address); + result = NetworkExtensions.FormatIPString(availableInterfaces.First().Address); _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result); return result; } @@ -782,14 +782,14 @@ namespace Jellyfin.Networking.Manager { if (intf.Subnet.Contains(source)) { - result = NetworkExtensions.FormatIpString(intf.Address); + result = NetworkExtensions.FormatIPString(intf.Address); _logger.LogDebug("{Source}: Found interface with matching subnet, using it as bind address: {Result}", source, result); return result; } } // Fallback to first available interface - result = NetworkExtensions.FormatIpString(availableInterfaces[0].Address); + result = NetworkExtensions.FormatIPString(availableInterfaces[0].Address); _logger.LogDebug("{Source}: No matching interfaces found, using preferred interface as bind address: {Result}", source, result); return result; } @@ -842,7 +842,7 @@ namespace Jellyfin.Networking.Manager ArgumentNullException.ThrowIfNull(address); // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. - if ((TrustAllIpv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + if ((TrustAllIPv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) || address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback)) { @@ -995,7 +995,7 @@ namespace Jellyfin.Networking.Manager if (bindAddress is not null) { - result = NetworkExtensions.FormatIpString(bindAddress); + result = NetworkExtensions.FormatIPString(bindAddress); _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result); return true; } @@ -1015,7 +1015,7 @@ namespace Jellyfin.Networking.Manager if (bindAddress is not null) { - result = NetworkExtensions.FormatIpString(bindAddress); + result = NetworkExtensions.FormatIPString(bindAddress); _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result); return true; } @@ -1049,14 +1049,14 @@ namespace Jellyfin.Networking.Manager { if (!IsInLocalNetwork(intf.Address) && intf.Subnet.Contains(source)) { - result = NetworkExtensions.FormatIpString(intf.Address); + result = NetworkExtensions.FormatIPString(intf.Address); _logger.LogDebug("{Source}: Found external interface with matching subnet, using it as bind address: {Result}", source, result); return true; } } // Fallback to first external interface. - result = NetworkExtensions.FormatIpString(extResult.First().Address); + result = NetworkExtensions.FormatIPString(extResult.First().Address); _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result); return true; } diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs index 463ca7321..b6af9baec 100644 --- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs @@ -63,9 +63,9 @@ namespace Jellyfin.Server.Extensions /// /// The application builder. /// The updated application builder. - public static IApplicationBuilder UseIpBasedAccessValidation(this IApplicationBuilder appBuilder) + public static IApplicationBuilder UseIPBasedAccessValidation(this IApplicationBuilder appBuilder) { - return appBuilder.UseMiddleware(); + return appBuilder.UseMiddleware(); } /// diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 1dfbb89fa..ea3c92011 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -271,26 +271,26 @@ namespace Jellyfin.Server.Extensions { if (IPAddress.TryParse(allowedProxies[i], out var addr)) { - AddIpAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); + AddIPAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } else if (NetworkExtensions.TryParseToSubnet(allowedProxies[i], out var subnet)) { if (subnet != null) { - AddIpAddress(config, options, subnet.Prefix, subnet.PrefixLength); + AddIPAddress(config, options, subnet.Prefix, subnet.PrefixLength); } } else if (NetworkExtensions.TryParseHost(allowedProxies[i], out var addresses)) { foreach (var address in addresses) { - AddIpAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); + AddIPAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } } } } - private static void AddIpAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength) + private static void AddIPAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength) { if ((!config.EnableIPv4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPv6 && addr.AddressFamily == AddressFamily.InterNetworkV6)) { diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 155f9fc8c..4afaf1217 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -190,7 +190,7 @@ namespace Jellyfin.Server mainApp.UseAuthorization(); mainApp.UseLanFiltering(); - mainApp.UseIpBasedAccessValidation(); + mainApp.UseIPBasedAccessValidation(); mainApp.UseWebSocketHandler(); mainApp.UseServerStartupMessage(); diff --git a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs index 6608704c0..a1056b7c8 100644 --- a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs +++ b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs @@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Extensions /// /// The HTTP context. /// The remote caller IP address. - public static IPAddress GetNormalizedRemoteIp(this HttpContext context) + public static IPAddress GetNormalizedRemoteIP(this HttpContext context) { // Default to the loopback address if no RemoteIpAddress is specified (i.e. during integration tests) var ip = context.Connection.RemoteIpAddress ?? IPAddress.Loopback; diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 68974f738..efd87a810 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -130,10 +130,10 @@ namespace MediaBrowser.Common.Net IReadOnlyList GetInternalBindAddresses(); /// - /// Checks if has access to the server. + /// Checks if has access to the server. /// - /// IP address of the client. + /// IP address of the client. /// True if it has access, otherwise false. - bool HasRemoteAccess(IPAddress remoteIp); + bool HasRemoteAccess(IPAddress remoteIP); } } diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 7c36081e6..cef4a5d96 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -126,11 +126,11 @@ namespace MediaBrowser.Common.Net /// /// Converts an IPAddress into a string. - /// Ipv6 addresses are returned in [ ], with their scope removed. + /// IPv6 addresses are returned in [ ], with their scope removed. /// /// Address to convert. /// URI safe conversion of the address. - public static string FormatIpString(IPAddress? address) + public static string FormatIPString(IPAddress? address) { if (address is null) { @@ -252,10 +252,10 @@ namespace MediaBrowser.Common.Net /// /// Host name to parse. /// Object representing the string, if it has successfully been parsed. - /// true if IPv4 is enabled. - /// true if IPv6 is enabled. + /// true if IPv4 is enabled. + /// true if IPv6 is enabled. /// true if the parsing is successful, false if not. - public static bool TryParseHost(string host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIpv4Enabled = true, bool isIpv6Enabled = false) + public static bool TryParseHost(string host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) { if (string.IsNullOrWhiteSpace(host)) { @@ -302,8 +302,8 @@ namespace MediaBrowser.Common.Net if (IPAddress.TryParse(host, out var address)) { - if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIpv4Enabled && isIpv6Enabled)) || - ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIpv4Enabled && !isIpv6Enabled))) + if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIPv4Enabled && isIPv6Enabled)) || + ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIPv4Enabled && !isIPv6Enabled))) { addresses = Array.Empty(); return false; @@ -338,11 +338,11 @@ namespace MediaBrowser.Common.Net addressBytes.Reverse(); } - uint ipAddress = BitConverter.ToUInt32(addressBytes, 0); + uint iPAddress = BitConverter.ToUInt32(addressBytes, 0); uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0); - uint broadCastIpAddress = ipAddress | ~ipMaskV4; + uint broadCastIPAddress = iPAddress | ~ipMaskV4; - return new IPAddress(BitConverter.GetBytes(broadCastIpAddress)); + return new IPAddress(BitConverter.GetBytes(broadCastIPAddress)); } } } diff --git a/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs b/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs index 987a3a908..c7489d57a 100644 --- a/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs +++ b/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs @@ -13,10 +13,10 @@ namespace MediaBrowser.Model.Dlna public Dictionary Headers { get; set; } - public IPAddress LocalIpAddress { get; set; } + public IPAddress LocalIPAddress { get; set; } public int LocalPort { get; set; } - public IPAddress RemoteIpAddress { get; set; } + public IPAddress RemoteIPAddress { get; set; } } } diff --git a/RSSDP/DeviceAvailableEventArgs.cs b/RSSDP/DeviceAvailableEventArgs.cs index 9d477ea9f..f933f258b 100644 --- a/RSSDP/DeviceAvailableEventArgs.cs +++ b/RSSDP/DeviceAvailableEventArgs.cs @@ -8,7 +8,7 @@ namespace Rssdp /// public sealed class DeviceAvailableEventArgs : EventArgs { - public IPAddress RemoteIpAddress { get; set; } + public IPAddress RemoteIPAddress { get; set; } private readonly DiscoveredSsdpDevice _DiscoveredDevice; diff --git a/RSSDP/ISsdpCommunicationsServer.cs b/RSSDP/ISsdpCommunicationsServer.cs index 571c66c10..95b0a1c70 100644 --- a/RSSDP/ISsdpCommunicationsServer.cs +++ b/RSSDP/ISsdpCommunicationsServer.cs @@ -33,13 +33,13 @@ namespace Rssdp.Infrastructure /// /// Sends a message to a particular address (uni or multicast) and port. /// - Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken); + Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIPAddress, CancellationToken cancellationToken); /// /// Sends a message to the SSDP multicast address and port. /// - Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken); - Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken); + Task SendMulticastMessage(string message, IPAddress fromLocalIPAddress, CancellationToken cancellationToken); + Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIPAddress, CancellationToken cancellationToken); /// /// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple and/or instances. diff --git a/RSSDP/RequestReceivedEventArgs.cs b/RSSDP/RequestReceivedEventArgs.cs index 5cf74bd75..b8b2249e4 100644 --- a/RSSDP/RequestReceivedEventArgs.cs +++ b/RSSDP/RequestReceivedEventArgs.cs @@ -13,16 +13,16 @@ namespace Rssdp.Infrastructure private readonly IPEndPoint _ReceivedFrom; - public IPAddress LocalIpAddress { get; private set; } + public IPAddress LocalIPAddress { get; private set; } /// /// Full constructor. /// - public RequestReceivedEventArgs(HttpRequestMessage message, IPEndPoint receivedFrom, IPAddress localIpAddress) + public RequestReceivedEventArgs(HttpRequestMessage message, IPEndPoint receivedFrom, IPAddress localIPAddress) { _Message = message; _ReceivedFrom = receivedFrom; - LocalIpAddress = localIpAddress; + LocalIPAddress = localIPAddress; } /// diff --git a/RSSDP/ResponseReceivedEventArgs.cs b/RSSDP/ResponseReceivedEventArgs.cs index 93262a460..e87ba1452 100644 --- a/RSSDP/ResponseReceivedEventArgs.cs +++ b/RSSDP/ResponseReceivedEventArgs.cs @@ -9,7 +9,7 @@ namespace Rssdp.Infrastructure /// public sealed class ResponseReceivedEventArgs : EventArgs { - public IPAddress LocalIpAddress { get; set; } + public IPAddress LocalIPAddress { get; set; } private readonly HttpResponseMessage _Message; diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index f70a598fb..5b8916d02 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -155,7 +155,7 @@ namespace Rssdp.Infrastructure /// /// Sends a message to a particular address (uni or multicast) and port. /// - public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { if (messageData is null) { @@ -164,7 +164,7 @@ namespace Rssdp.Infrastructure ThrowIfDisposed(); - var sockets = GetSendSockets(fromLocalIpAddress, destination); + var sockets = GetSendSockets(fromlocalIPAddress, destination); if (sockets.Count == 0) { @@ -200,19 +200,19 @@ namespace Rssdp.Infrastructure } } - private List GetSendSockets(IPAddress fromLocalIpAddress, IPEndPoint destination) + private List GetSendSockets(IPAddress fromlocalIPAddress, IPEndPoint destination) { EnsureSendSocketCreated(); lock (_SendSocketSynchroniser) { - var sockets = _sendSockets.Where(s => s.AddressFamily == fromLocalIpAddress.AddressFamily); + var sockets = _sendSockets.Where(s => s.AddressFamily == fromlocalIPAddress.AddressFamily); // Send from the Any socket and the socket with the matching address - if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetwork) + if (fromlocalIPAddress.AddressFamily == AddressFamily.InterNetwork) { sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any) - || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromLocalIpAddress)); + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromlocalIPAddress)); // If sending to the loopback address, filter the socket list as well if (destination.Address.Equals(IPAddress.Loopback)) @@ -221,10 +221,10 @@ namespace Rssdp.Infrastructure || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Loopback)); } } - else if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetworkV6) + else if (fromlocalIPAddress.AddressFamily == AddressFamily.InterNetworkV6) { sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any) - || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromLocalIpAddress)); + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromlocalIPAddress)); // If sending to the loopback address, filter the socket list as well if (destination.Address.Equals(IPAddress.IPv6Loopback)) @@ -238,15 +238,15 @@ namespace Rssdp.Infrastructure } } - public Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + public Task SendMulticastMessage(string message, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { - return SendMulticastMessage(message, SsdpConstants.UdpResendCount, fromLocalIpAddress, cancellationToken); + return SendMulticastMessage(message, SsdpConstants.UdpResendCount, fromlocalIPAddress, cancellationToken); } /// /// Sends a message to the SSDP multicast address and port. /// - public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { if (message is null) { @@ -269,7 +269,7 @@ namespace Rssdp.Infrastructure new IPEndPoint( IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), SsdpConstants.MulticastPort), - fromLocalIpAddress, + fromlocalIPAddress, cancellationToken).ConfigureAwait(false); await Task.Delay(100, cancellationToken).ConfigureAwait(false); @@ -328,14 +328,14 @@ namespace Rssdp.Infrastructure } } - private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) + private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromlocalIPAddress, CancellationToken cancellationToken) { var sockets = _sendSockets; if (sockets is not null) { sockets = sockets.ToList(); - var tasks = sockets.Where(s => (fromLocalIpAddress is null || fromLocalIpAddress.Equals(((IPEndPoint)s.LocalEndPoint).Address))) + var tasks = sockets.Where(s => (fromlocalIPAddress is null || fromlocalIPAddress.Equals(((IPEndPoint)s.LocalEndPoint).Address))) .Select(s => SendFromSocket(s, messageData, destination, cancellationToken)); return Task.WhenAll(tasks); } @@ -458,13 +458,13 @@ namespace Rssdp.Infrastructure } } - private void ProcessMessage(string data, IPEndPoint endPoint, IPAddress receivedOnLocalIpAddress) + private void ProcessMessage(string data, IPEndPoint endPoint, IPAddress receivedOnlocalIPAddress) { // Responses start with the HTTP version, prefixed with HTTP/ while // requests start with a method which can vary and might be one we haven't // seen/don't know. We'll check if this message is a request or a response // by checking for the HTTP/ prefix on the start of the message. - _logger.LogDebug("Received data from {From} on {Port} at {Address}:\n{Data}", endPoint.Address, endPoint.Port, receivedOnLocalIpAddress, data); + _logger.LogDebug("Received data from {From} on {Port} at {Address}:\n{Data}", endPoint.Address, endPoint.Port, receivedOnlocalIPAddress, data); if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase)) { HttpResponseMessage responseMessage = null; @@ -479,7 +479,7 @@ namespace Rssdp.Infrastructure if (responseMessage is not null) { - OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress); + OnResponseReceived(responseMessage, endPoint, receivedOnlocalIPAddress); } } else @@ -496,12 +496,12 @@ namespace Rssdp.Infrastructure if (requestMessage is not null) { - OnRequestReceived(requestMessage, endPoint, receivedOnLocalIpAddress); + OnRequestReceived(requestMessage, endPoint, receivedOnlocalIPAddress); } } } - private void OnRequestReceived(HttpRequestMessage data, IPEndPoint remoteEndPoint, IPAddress receivedOnLocalIpAddress) + private void OnRequestReceived(HttpRequestMessage data, IPEndPoint remoteEndPoint, IPAddress receivedOnlocalIPAddress) { // SSDP specification says only * is currently used but other uri's might // be implemented in the future and should be ignored unless understood. @@ -514,18 +514,18 @@ namespace Rssdp.Infrastructure var handlers = this.RequestReceived; if (handlers is not null) { - handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress)); + handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnlocalIPAddress)); } } - private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIpAddress) + private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIPAddress) { var handlers = this.ResponseReceived; if (handlers is not null) { handlers(this, new ResponseReceivedEventArgs(data, endPoint) { - LocalIpAddress = localIpAddress + LocalIPAddress = localIPAddress }); } } diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index 25c3b4c4e..9d756d0d4 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -240,7 +240,7 @@ namespace Rssdp.Infrastructure /// Raises the event. /// /// - protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IpAddress) + protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IPAddress) { if (this.IsDisposed) { @@ -252,7 +252,7 @@ namespace Rssdp.Infrastructure { handlers(this, new DeviceAvailableEventArgs(device, isNewDevice) { - RemoteIpAddress = IpAddress + RemoteIPAddress = IPAddress }); } } @@ -318,7 +318,7 @@ namespace Rssdp.Infrastructure } } - private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IPAddress IpAddress) + private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IPAddress IPAddress) { bool isNewDevice = false; lock (_Devices) @@ -336,17 +336,17 @@ namespace Rssdp.Infrastructure } } - DeviceFound(device, isNewDevice, IpAddress); + DeviceFound(device, isNewDevice, IPAddress); } - private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IpAddress) + private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IPAddress) { if (!NotificationTypeMatchesFilter(device)) { return; } - OnDeviceAvailable(device, isNewDevice, IpAddress); + OnDeviceAvailable(device, isNewDevice, IPAddress); } private bool NotificationTypeMatchesFilter(DiscoveredSsdpDevice device) @@ -378,7 +378,7 @@ namespace Rssdp.Infrastructure return _CommunicationsServer.SendMulticastMessage(message, null, cancellationToken); } - private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress IpAddress) + private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress IPAddress) { if (!message.IsSuccessStatusCode) { @@ -398,11 +398,11 @@ namespace Rssdp.Infrastructure ResponseHeaders = message.Headers }; - AddOrUpdateDiscoveredDevice(device, IpAddress); + AddOrUpdateDiscoveredDevice(device, IPAddress); } } - private void ProcessNotificationMessage(HttpRequestMessage message, IPAddress IpAddress) + private void ProcessNotificationMessage(HttpRequestMessage message, IPAddress IPAddress) { if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0) { @@ -412,7 +412,7 @@ namespace Rssdp.Infrastructure var notificationType = GetFirstHeaderStringValue("NTS", message); if (String.Compare(notificationType, SsdpConstants.SsdpKeepAliveNotification, StringComparison.OrdinalIgnoreCase) == 0) { - ProcessAliveNotification(message, IpAddress); + ProcessAliveNotification(message, IPAddress); } else if (String.Compare(notificationType, SsdpConstants.SsdpByeByeNotification, StringComparison.OrdinalIgnoreCase) == 0) { @@ -420,7 +420,7 @@ namespace Rssdp.Infrastructure } } - private void ProcessAliveNotification(HttpRequestMessage message, IPAddress IpAddress) + private void ProcessAliveNotification(HttpRequestMessage message, IPAddress IPAddress) { var location = GetFirstHeaderUriValue("Location", message); if (location is not null) @@ -435,7 +435,7 @@ namespace Rssdp.Infrastructure ResponseHeaders = message.Headers }; - AddOrUpdateDiscoveredDevice(device, IpAddress); + AddOrUpdateDiscoveredDevice(device, IPAddress); } } @@ -651,7 +651,7 @@ namespace Rssdp.Infrastructure private void CommsServer_ResponseReceived(object sender, ResponseReceivedEventArgs e) { - ProcessSearchResponseMessage(e.Message, e.LocalIpAddress); + ProcessSearchResponseMessage(e.Message, e.LocalIPAddress); } private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e) diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index 40d93b6c0..8b5551899 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -224,7 +224,7 @@ namespace Rssdp.Infrastructure string mx, string searchTarget, IPEndPoint remoteEndPoint, - IPAddress receivedOnlocalIpAddress, + IPAddress receivedOnlocalIPAddress, CancellationToken cancellationToken) { if (String.IsNullOrEmpty(searchTarget)) @@ -297,9 +297,9 @@ namespace Rssdp.Infrastructure { var root = device.ToRootDevice(); - if (!_sendOnlyMatchedHost || root.Address.Equals(receivedOnlocalIpAddress)) + if (!_sendOnlyMatchedHost || root.Address.Equals(receivedOnlocalIPAddress)) { - SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken); + SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIPAddress, cancellationToken); } } } @@ -314,22 +314,22 @@ namespace Rssdp.Infrastructure private void SendDeviceSearchResponses( SsdpDevice device, IPEndPoint endPoint, - IPAddress receivedOnlocalIpAddress, + IPAddress receivedOnlocalIPAddress, CancellationToken cancellationToken) { bool isRootDevice = (device as SsdpRootDevice) is not null; if (isRootDevice) { - SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken); + SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIPAddress, cancellationToken); if (this.SupportPnpRootDevice) { - SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken); + SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint, receivedOnlocalIPAddress, cancellationToken); } } - SendSearchResponse(device.Udn, device, device.Udn, endPoint, receivedOnlocalIpAddress, cancellationToken); + SendSearchResponse(device.Udn, device, device.Udn, endPoint, receivedOnlocalIPAddress, cancellationToken); - SendSearchResponse(device.FullDeviceType, device, GetUsn(device.Udn, device.FullDeviceType), endPoint, receivedOnlocalIpAddress, cancellationToken); + SendSearchResponse(device.FullDeviceType, device, GetUsn(device.Udn, device.FullDeviceType), endPoint, receivedOnlocalIPAddress, cancellationToken); } private string GetUsn(string udn, string fullDeviceType) @@ -342,7 +342,7 @@ namespace Rssdp.Infrastructure SsdpDevice device, string uniqueServiceName, IPEndPoint endPoint, - IPAddress receivedOnlocalIpAddress, + IPAddress receivedOnlocalIPAddress, CancellationToken cancellationToken) { const string header = "HTTP/1.1 200 OK"; @@ -366,7 +366,7 @@ namespace Rssdp.Infrastructure await _CommsServer.SendMessage( Encoding.UTF8.GetBytes(message), endPoint, - receivedOnlocalIpAddress, + receivedOnlocalIPAddress, cancellationToken) .ConfigureAwait(false); } @@ -625,7 +625,7 @@ namespace Rssdp.Infrastructure // else if (!e.Message.Headers.Contains("MAN")) // WriteTrace("Ignoring search request - missing MAN header."); // else - ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom, e.LocalIpAddress, CancellationToken.None); + ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom, e.LocalIPAddress, CancellationToken.None); } } diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 10706e9c2..d51ce19d7 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -97,7 +97,7 @@ namespace Jellyfin.Networking.Tests /// Checks if IPv4 address is within a defined subnet. /// /// Network mask. - /// IP Address. + /// IP Address. [Theory] [InlineData("192.168.5.85/24", "192.168.5.1")] [InlineData("192.168.5.85/24", "192.168.5.254")] @@ -282,7 +282,7 @@ namespace Jellyfin.Networking.Tests [InlineData("185.10.10.10", "185.10.10.10", false)] [InlineData("", "100.100.100.100", false)] - public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIPsInWhitelist(string addresses, string remoteIp, bool denied) + public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIPsInWhitelist(string addresses, string remoteIP, bool denied) { // 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. @@ -294,7 +294,7 @@ namespace Jellyfin.Networking.Tests }; using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied); + Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIP)), denied); } [Theory] @@ -302,7 +302,7 @@ namespace Jellyfin.Networking.Tests [InlineData("185.10.10.10", "185.10.10.10", true)] [InlineData("", "100.100.100.100", false)] - public void HasRemoteAccess_GivenBlacklist_BlacklistTheIPs(string addresses, string remoteIp, bool denied) + public void HasRemoteAccess_GivenBlacklist_BlacklistTheIPs(string addresses, string remoteIP, bool denied) { // 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. @@ -315,7 +315,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied); + Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIP)), denied); } [Theory] -- cgit v1.2.3 From a5bfeb28aa2c92e6e58f5f00e5651807794ac8ef Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Mon, 20 Feb 2023 21:51:15 +0100 Subject: Apply review suggestions --- Jellyfin.Networking/Manager/NetworkManager.cs | 141 ++++++++++++--------- MediaBrowser.Common/Net/INetworkManager.cs | 6 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 103 +++++++-------- RSSDP/SsdpCommunicationsServer.cs | 2 +- .../Jellyfin.Networking.Tests/NetworkParseTests.cs | 4 +- 5 files changed, 138 insertions(+), 118 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index dd90a5b51..f0f95f5fc 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -26,11 +26,6 @@ namespace Jellyfin.Networking.Manager /// private readonly object _initLock; - /// - /// List of all interface MAC addresses. - /// - private readonly List _macAddresses; - private readonly ILogger _logger; private readonly IConfigurationManager _configurationManager; @@ -40,30 +35,35 @@ namespace Jellyfin.Networking.Manager /// /// Holds the published server URLs and the IPs to use them on. /// - private readonly Dictionary _publishedServerUrls; + private IReadOnlyDictionary _publishedServerUrls; - private List _remoteAddressFilter; + private IReadOnlyList _remoteAddressFilter; /// /// Used to stop "event-racing conditions". /// private bool _eventfire; + /// + /// List of all interface MAC addresses. + /// + private IReadOnlyList _macAddresses; + /// /// Dictionary containing interface addresses and their subnets. /// - private List _interfaces; + private IReadOnlyList _interfaces; /// /// Unfiltered user defined LAN subnets () /// or internal interface network subnets if undefined by user. /// - private List _lanSubnets; + private IReadOnlyList _lanSubnets; /// /// User defined list of subnets to excluded from the LAN. /// - private List _excludedSubnets; + private IReadOnlyList _excludedSubnets; /// /// True if this object is disposed. @@ -127,7 +127,7 @@ namespace Jellyfin.Networking.Manager /// /// Gets the Published server override list. /// - public Dictionary PublishedServerUrls => _publishedServerUrls; + public IReadOnlyDictionary PublishedServerUrls => _publishedServerUrls; /// public void Dispose() @@ -206,8 +206,8 @@ namespace Jellyfin.Networking.Manager { _logger.LogDebug("Refreshing interfaces."); - _interfaces.Clear(); - _macAddresses.Clear(); + var interfaces = new List(); + var macAddresses = new List(); try { @@ -224,7 +224,7 @@ namespace Jellyfin.Networking.Manager // Populate MAC list if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && PhysicalAddress.None.Equals(mac)) { - _macAddresses.Add(mac); + macAddresses.Add(mac); } // Populate interface list @@ -236,7 +236,7 @@ namespace Jellyfin.Networking.Manager interfaceObject.Index = ipProperties.GetIPv4Properties().Index; interfaceObject.Name = adapter.Name; - _interfaces.Add(interfaceObject); + interfaces.Add(interfaceObject); } else if (IsIPv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) { @@ -244,7 +244,7 @@ namespace Jellyfin.Networking.Manager interfaceObject.Index = ipProperties.GetIPv6Properties().Index; interfaceObject.Name = adapter.Name; - _interfaces.Add(interfaceObject); + interfaces.Add(interfaceObject); } } } @@ -265,23 +265,26 @@ namespace Jellyfin.Networking.Manager } // If no interfaces are found, fallback to loopback interfaces. - if (_interfaces.Count == 0) + if (interfaces.Count == 0) { _logger.LogWarning("No interface information available. Using loopback interface(s)."); if (IsIPv4Enabled && !IsIPv6Enabled) { - _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); + interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); } if (!IsIPv4Enabled && IsIPv6Enabled) { - _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); + interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } } - _logger.LogDebug("Discovered {NumberOfInterfaces} interfaces.", _interfaces.Count); - _logger.LogDebug("Interfaces addresses: {Addresses}", _interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString())); + _logger.LogDebug("Discovered {NumberOfInterfaces} interfaces.", interfaces.Count); + _logger.LogDebug("Interfaces addresses: {Addresses}", interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString())); + + _macAddresses = macAddresses; + _interfaces = interfaces; } } @@ -297,37 +300,38 @@ namespace Jellyfin.Networking.Manager // Get configuration options var subnets = config.LocalNetworkSubnets; - if (!NetworkExtensions.TryParseToSubnets(subnets, out _lanSubnets, false)) - { - _lanSubnets.Clear(); - } - - if (!NetworkExtensions.TryParseToSubnets(subnets, out _excludedSubnets, true)) - { - _excludedSubnets.Clear(); - } - // If no LAN addresses are specified, all private subnets and Loopback are deemed to be the LAN - if (_lanSubnets.Count == 0) + if (!NetworkExtensions.TryParseToSubnets(subnets, out var lanSubnets, false) || lanSubnets.Count == 0) { _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); + var fallbackLanSubnets = new List(); if (IsIPv6Enabled) { - _lanSubnets.Add(new IPNetwork(IPAddress.IPv6Loopback, 128)); // RFC 4291 (Loopback) - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // RFC 4291 (Site local) - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // RFC 4193 (Unique local) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.IPv6Loopback, 128)); // RFC 4291 (Loopback) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // RFC 4291 (Site local) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // RFC 4193 (Unique local) } if (IsIPv4Enabled) { - _lanSubnets.Add(new IPNetwork(IPAddress.Loopback, 8)); // RFC 5735 (Loopback) - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); // RFC 1918 (private) - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("172.16.0.0"), 12)); // RFC 1918 (private) - _lanSubnets.Add(new IPNetwork(IPAddress.Parse("192.168.0.0"), 16)); // RFC 1918 (private) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Loopback, 8)); // RFC 5735 (Loopback) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); // RFC 1918 (private) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("172.16.0.0"), 12)); // RFC 1918 (private) + fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("192.168.0.0"), 16)); // RFC 1918 (private) } + + _lanSubnets = fallbackLanSubnets; + } + else + { + _lanSubnets = lanSubnets; } + _excludedSubnets = NetworkExtensions.TryParseToSubnets(subnets, out var excludedSubnets, true) + ? excludedSubnets + : new List(); + _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)); @@ -342,26 +346,27 @@ namespace Jellyfin.Networking.Manager lock (_initLock) { // Respect explicit bind addresses + var interfaces = _interfaces.ToList(); var localNetworkAddresses = config.LocalNetworkAddresses; if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses[0])) { var bindAddresses = localNetworkAddresses.Select(p => NetworkExtensions.TryParseToSubnet(p, out var network) ? network.Prefix - : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)) + : (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(); + interfaces = interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList(); if (bindAddresses.Contains(IPAddress.Loopback)) { - _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); + interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); } if (bindAddresses.Contains(IPAddress.IPv6Loopback)) { - _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); + interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } } @@ -377,7 +382,7 @@ namespace Jellyfin.Networking.Manager { foreach (var virtualInterfacePrefix in virtualInterfacePrefixes) { - _interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase)); + interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase)); } } } @@ -385,16 +390,17 @@ namespace Jellyfin.Networking.Manager // Remove all IPv4 interfaces if IPv4 is disabled if (!IsIPv4Enabled) { - _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork); + interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork); } // Remove all IPv6 interfaces if IPv6 is disabled if (!IsIPv6Enabled) { - _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); + interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); } - _logger.LogInformation("Using bind addresses: {0}", _interfaces.OrderByDescending(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.Address)); + _logger.LogInformation("Using bind addresses: {0}", interfaces.OrderByDescending(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.Address)); + _interfaces = interfaces; } } @@ -410,10 +416,11 @@ namespace Jellyfin.Networking.Manager if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First())) { // Parse all IPs with netmask to a subnet + var remoteAddressFilter = new List(); var remoteFilteredSubnets = remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(); - if (!NetworkExtensions.TryParseToSubnets(remoteFilteredSubnets, out _remoteAddressFilter, false)) + if (NetworkExtensions.TryParseToSubnets(remoteFilteredSubnets, out var remoteAddressFilterResult, false)) { - _remoteAddressFilter.Clear(); + remoteAddressFilter = remoteAddressFilterResult.ToList(); } // Parse everything else as an IP and construct subnet with a single IP @@ -422,9 +429,11 @@ namespace Jellyfin.Networking.Manager { if (IPAddress.TryParse(ip, out var ipp)) { - _remoteAddressFilter.Add(new IPNetwork(ipp, ipp.AddressFamily == AddressFamily.InterNetwork ? 32 : 128)); + remoteAddressFilter.Add(new IPNetwork(ipp, ipp.AddressFamily == AddressFamily.InterNetwork ? 32 : 128)); } } + + _remoteAddressFilter = remoteAddressFilter; } } } @@ -440,8 +449,8 @@ namespace Jellyfin.Networking.Manager { lock (_initLock) { - _publishedServerUrls.Clear(); - string[] overrides = config.PublishedServerUriBySubnet; + var publishedServerUrls = new Dictionary(); + var overrides = config.PublishedServerUriBySubnet; foreach (var entry in overrides) { @@ -456,31 +465,31 @@ namespace Jellyfin.Networking.Manager var identifier = parts[0]; if (string.Equals(identifier, "all", StringComparison.OrdinalIgnoreCase)) { - _publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement; + publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement; } else if (string.Equals(identifier, "external", StringComparison.OrdinalIgnoreCase)) { - _publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; - _publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement; + publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; + publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = 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; + 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; + publishedServerUrls[data] = replacement; } else if (TryParseInterface(identifier, out var ifaces)) { foreach (var iface in ifaces) { - _publishedServerUrls[iface] = replacement; + publishedServerUrls[iface] = replacement; } } else @@ -488,6 +497,8 @@ namespace Jellyfin.Networking.Manager _logger.LogError("Unable to parse bind override: {Entry}", entry); } } + + _publishedServerUrls = publishedServerUrls; } } @@ -520,6 +531,7 @@ namespace Jellyfin.Networking.Manager { // Format is ,,: . Set index to -ve to simulate a gateway. var interfaceList = MockNetworkSettings.Split('|'); + var interfaces = new List(); foreach (var details in interfaceList) { var parts = details.Split(','); @@ -531,7 +543,7 @@ namespace Jellyfin.Networking.Manager { var data = new IPData(address, subnet, parts[2]); data.Index = index; - _interfaces.Add(data); + interfaces.Add(data); } } else @@ -539,6 +551,8 @@ namespace Jellyfin.Networking.Manager _logger.LogWarning("Could not parse mock interface settings: {Part}", details); } } + + _interfaces = interfaces; } EnforceBindSettings(config); @@ -565,11 +579,12 @@ namespace Jellyfin.Networking.Manager } /// - public bool TryParseInterface(string intf, out List result) + public bool TryParseInterface(string intf, out IReadOnlyList result) { - result = new List(); + var resultList = new List(); if (string.IsNullOrEmpty(intf) || _interfaces is null) { + result = resultList.AsReadOnly(); return false; } @@ -585,13 +600,15 @@ namespace Jellyfin.Networking.Manager if ((IsIPv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || (IsIPv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) { - result.Add(iface); + resultList.Add(iface); } } + result = resultList.AsReadOnly(); return true; } + result = resultList.AsReadOnly(); return false; } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 1a3176b58..a92b751f2 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -30,7 +30,7 @@ namespace MediaBrowser.Common.Net /// /// Calculates the list of interfaces to use for Kestrel. /// - /// A List{IPData} object containing all the interfaces to bind. + /// A IReadOnlyList{IPData} object containing all the interfaces to bind. /// If all the interfaces are specified, and none are excluded, it returns zero items /// to represent any address. /// When false, return or for all interfaces. @@ -39,7 +39,7 @@ namespace MediaBrowser.Common.Net /// /// Returns a list containing the loopback interfaces. /// - /// List{IPData}. + /// IReadOnlyList{IPData}. IReadOnlyList GetLoopbacks(); /// @@ -120,7 +120,7 @@ namespace MediaBrowser.Common.Net /// Interface name. /// Resulting object's IP addresses, if successful. /// Success of the operation. - bool TryParseInterface(string intf, out List result); + bool TryParseInterface(string intf, out IReadOnlyList result); /// /// Returns all internal (LAN) bind interface addresses. diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index cef4a5d96..227f0483f 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; +using Jellyfin.Extensions; using Microsoft.AspNetCore.HttpOverrides; namespace MediaBrowser.Common.Net @@ -193,71 +194,64 @@ namespace MediaBrowser.Common.Net /// An . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. - public static bool TryParseToSubnet(string value, out IPNetwork result, bool negated = false) + public static bool TryParseToSubnet(ReadOnlySpan value, out IPNetwork result, bool negated = false) { result = new IPNetwork(IPAddress.None, 32); - - if (string.IsNullOrEmpty(value)) - { - return false; - } - - var splitString = value.Trim().Split("/"); - var ipBlock = splitString[0]; - - var address = IPAddress.None; - if (negated && ipBlock.StartsWith('!') && IPAddress.TryParse(ipBlock[1..], out var tmpAddress)) - { - address = tmpAddress; - } - else if (!negated && IPAddress.TryParse(ipBlock, out tmpAddress)) + var splitString = value.Trim().Split('/'); + if (splitString.MoveNext()) { - address = tmpAddress; - } + var ipBlock = splitString.Current; + var address = IPAddress.None; + if (negated && ipBlock.StartsWith("!") && IPAddress.TryParse(ipBlock[1..], out var tmpAddress)) + { + address = tmpAddress; + } + else if (!negated && IPAddress.TryParse(ipBlock, out tmpAddress)) + { + address = tmpAddress; + } - if (address != IPAddress.None && address is not null) - { - if (splitString.Length > 1) + if (address != IPAddress.None) { - var subnetBlock = splitString[1]; - if (int.TryParse(subnetBlock, out var netmask)) + if (splitString.MoveNext()) { - result = new IPNetwork(address, netmask); + var subnetBlock = splitString.Current; + if (int.TryParse(subnetBlock, out var netmask)) + { + result = new IPNetwork(address, netmask); + } + else if (IPAddress.TryParse(subnetBlock, out var netmaskAddress)) + { + result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + } } - else if (IPAddress.TryParse(subnetBlock, out var netmaskAddress)) + else if (address.AddressFamily == AddressFamily.InterNetwork) { - result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + result = new IPNetwork(address, 32); + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + result = new IPNetwork(address, 128); } - } - else if (address.AddressFamily == AddressFamily.InterNetwork) - { - result = new IPNetwork(address, 32); - } - else if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - result = new IPNetwork(address, 128); - } - } - if (!result.Prefix.Equals(IPAddress.None)) - { - return true; + return true; + } } return false; } /// - /// Attempts to parse a host string. + /// Attempts to parse a host span. /// /// Host name to parse. - /// Object representing the string, if it has successfully been parsed. + /// Object representing the span, if it has successfully been parsed. /// true if IPv4 is enabled. /// true if IPv6 is enabled. /// true if the parsing is successful, false if not. - public static bool TryParseHost(string host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) + public static bool TryParseHost(ReadOnlySpan host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) { - if (string.IsNullOrWhiteSpace(host)) + if (host.IsEmpty) { addresses = Array.Empty(); return false; @@ -268,19 +262,24 @@ namespace MediaBrowser.Common.Net // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. if (host[0] == '[') { - int i = host.IndexOf(']', StringComparison.Ordinal); + int i = host.IndexOf("]", StringComparison.Ordinal); if (i != -1) { - return TryParseHost(host.Remove(i)[1..], out addresses); + return TryParseHost(host[1..(i - 1)], out addresses); } addresses = Array.Empty(); return false; } - var hosts = host.Split(':'); + var hosts = new List(); + var splitSpan = host.Split(':'); + while (splitSpan.MoveNext()) + { + hosts.Add(splitSpan.Current.ToString()); + } - if (hosts.Length <= 2) + if (hosts.Count <= 2) { // Is hostname or hostname:port if (_fqdnRegex.IsMatch(hosts[0])) @@ -315,10 +314,14 @@ namespace MediaBrowser.Common.Net return true; } } - else if (hosts.Length <= 9 && IPAddress.TryParse(host.Split('/')[0], out var address)) // 8 octets + port + else if (hosts.Count <= 9) // 8 octets + port { - addresses = new[] { address }; - return true; + splitSpan = host.Split('/'); + if (splitSpan.MoveNext() && IPAddress.TryParse(splitSpan.Current, out var address)) + { + addresses = new[] { address }; + return true; + } } addresses = Array.Empty(); diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index 5b8916d02..0dce6c3bf 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -428,7 +428,7 @@ namespace Rssdp.Infrastructure if (result.ReceivedBytes > 0) { var remoteEndpoint = (IPEndPoint)result.RemoteEndPoint; - var localEndpointAdapter = _networkManager.GetAllBindInterfaces().Where(a => a.Index == result.PacketInformation.Interface).First(); + var localEndpointAdapter = _networkManager.GetAllBindInterfaces().First(a => a.Index == result.PacketInformation.Interface); ProcessMessage( UTF8Encoding.UTF8.GetString(receiveBuffer, 0, result.ReceivedBytes), diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index d51ce19d7..8b7df0470 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -203,7 +203,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - _ = nm.TryParseInterface(result, out List? resultObj); + _ = nm.TryParseInterface(result, out IReadOnlyList? resultObj); // Check to see if dns resolution is working. If not, skip test. _ = NetworkExtensions.TryParseHost(source, out var host); @@ -266,7 +266,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - if (nm.TryParseInterface(result, out List? resultObj) && resultObj is not null) + if (nm.TryParseInterface(result, out IReadOnlyList? resultObj) && resultObj is not null) { // Parse out IPAddresses so we can do a string comparison (ignore subnet masks). result = resultObj.First().Address.ToString(); -- cgit v1.2.3 From a381cd3c7652e4c802e697e367370f4dba3987f6 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 25 May 2023 17:10:53 +0200 Subject: Apply review suggestions --- MediaBrowser.Common/Net/NetworkExtensions.cs | 52 +++++++++++++++------------- 1 file changed, 28 insertions(+), 24 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 227f0483f..8a14bf48d 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -93,31 +93,36 @@ namespace MediaBrowser.Common.Net ArgumentNullException.ThrowIfNull(mask); byte cidrnet = 0; - if (!mask.Equals(IPAddress.Any)) + if (mask.Equals(IPAddress.Any)) { - // GetAddressBytes - Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; - mask.TryWriteBytes(bytes, out _); + return cidrnet; + } + + // GetAddressBytes + Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; + if (!mask.TryWriteBytes(bytes, out var bytesWritten)) + { + Console.WriteLine("Unable to write address bytes, only {Bytes} bytes written.", bytesWritten); + } - var zeroed = false; - for (var i = 0; i < bytes.Length; i++) + var zeroed = false; + for (var i = 0; i < bytes.Length; i++) + { + for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1) { - for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1) + if (zeroed) { - if (zeroed) - { - // Invalid netmask. - return (byte)~cidrnet; - } + // Invalid netmask. + return (byte)~cidrnet; + } - if ((v & 0x80) == 0) - { - zeroed = true; - } - else - { - cidrnet++; - } + if ((v & 0x80) == 0) + { + zeroed = true; + } + else + { + cidrnet++; } } } @@ -273,10 +278,9 @@ namespace MediaBrowser.Common.Net } var hosts = new List(); - var splitSpan = host.Split(':'); - while (splitSpan.MoveNext()) + foreach (var splitSpan in host.Split(':')) { - hosts.Add(splitSpan.Current.ToString()); + hosts.Add(splitSpan.ToString()); } if (hosts.Count <= 2) @@ -316,7 +320,7 @@ namespace MediaBrowser.Common.Net } else if (hosts.Count <= 9) // 8 octets + port { - splitSpan = host.Split('/'); + var splitSpan = host.Split('/'); if (splitSpan.MoveNext() && IPAddress.TryParse(splitSpan.Current, out var address)) { addresses = new[] { address }; -- cgit v1.2.3 From 9b0e44019a350ee89befcc92edcb95ae20787cf9 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Sun, 2 Jul 2023 12:34:50 +0200 Subject: Apply review suggestions --- Jellyfin.Networking/Manager/NetworkManager.cs | 7 +++-- MediaBrowser.Common/Net/INetworkManager.cs | 3 +- MediaBrowser.Common/Net/NetworkExtensions.cs | 35 +++++++++++----------- .../Jellyfin.Networking.Tests/NetworkParseTests.cs | 11 +++---- 4 files changed, 30 insertions(+), 26 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 1b1e91e9f..7d21c26cd 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net; @@ -380,7 +381,7 @@ namespace Jellyfin.Networking.Manager // Remove all interfaces matching any virtual machine interface prefix if (config.IgnoreVirtualInterfaces) { - // Remove potentially exisiting * and split config string into prefixes + // Remove potentially existing * and split config string into prefixes var virtualInterfacePrefixes = config.VirtualInterfaceNames .Select(i => i.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase)); @@ -587,7 +588,7 @@ namespace Jellyfin.Networking.Manager } /// - public bool TryParseInterface(string intf, out IReadOnlyList result) + public bool TryParseInterface(string intf, [NotNullWhen(true)] out IReadOnlyList? result) { var resultList = new List(); if (string.IsNullOrEmpty(intf) || _interfaces is null) @@ -660,7 +661,7 @@ namespace Jellyfin.Networking.Manager /// public IReadOnlyList GetLoopbacks() { - if (!(IsIPv4Enabled && IsIPv4Enabled)) + if (!IsIPv4Enabled && !IsIPv6Enabled) { return Array.Empty(); } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index a92b751f2..c51090e38 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.NetworkInformation; using MediaBrowser.Model.Net; @@ -120,7 +121,7 @@ namespace MediaBrowser.Common.Net /// Interface name. /// Resulting object's IP addresses, if successful. /// Success of the operation. - bool TryParseInterface(string intf, out IReadOnlyList result); + bool TryParseInterface(string intf, [NotNullWhen(true)] out IReadOnlyList? result); /// /// Returns all internal (LAN) bind interface addresses. diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 8a14bf48d..ae85583a5 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -166,28 +166,30 @@ namespace MediaBrowser.Common.Net /// Collection of . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. - public static bool TryParseToSubnets(string[] values, out List result, bool negated = false) + public static bool TryParseToSubnets(string[] values, [NotNullWhen(true)] out IReadOnlyList? result, bool negated = false) { - result = new List(); - if (values is null || values.Length == 0) { + result = null; return false; } + var tmpResult = new List(); for (int a = 0; a < values.Length; a++) { if (TryParseToSubnet(values[a], out var innerResult, negated)) { - result.Add(innerResult); + tmpResult.Add(innerResult); } } - if (result.Count > 0) + if (tmpResult.Count > 0) { + result = tmpResult; return true; } + result = null; return false; } @@ -199,9 +201,8 @@ namespace MediaBrowser.Common.Net /// An . /// Boolean signaling if negated or not negated values should be parsed. /// True if parsing was successful. - public static bool TryParseToSubnet(ReadOnlySpan value, out IPNetwork result, bool negated = false) + public static bool TryParseToSubnet(ReadOnlySpan value, [NotNullWhen(true)] out IPNetwork? result, bool negated = false) { - result = new IPNetwork(IPAddress.None, 32); var splitString = value.Trim().Split('/'); if (splitString.MoveNext()) { @@ -224,25 +225,28 @@ namespace MediaBrowser.Common.Net if (int.TryParse(subnetBlock, out var netmask)) { result = new IPNetwork(address, netmask); + return true; } else if (IPAddress.TryParse(subnetBlock, out var netmaskAddress)) { result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)); + return true; } } else if (address.AddressFamily == AddressFamily.InterNetwork) { result = new IPNetwork(address, 32); + return true; } else if (address.AddressFamily == AddressFamily.InterNetworkV6) { result = new IPNetwork(address, 128); + return true; } - - return true; } } + result = null; return false; } @@ -254,11 +258,11 @@ namespace MediaBrowser.Common.Net /// true if IPv4 is enabled. /// true if IPv6 is enabled. /// true if the parsing is successful, false if not. - public static bool TryParseHost(ReadOnlySpan host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) + public static bool TryParseHost(ReadOnlySpan host, [NotNullWhen(true)] out IPAddress[]? addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) { if (host.IsEmpty) { - addresses = Array.Empty(); + addresses = null; return false; } @@ -301,9 +305,7 @@ namespace MediaBrowser.Common.Net } // Is an IP4 or IP4:port - host = hosts[0].Split('/')[0]; - - if (IPAddress.TryParse(host, out var address)) + if (IPAddress.TryParse(hosts[0].AsSpan().LeftPart('/'), out var address)) { if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIPv4Enabled && isIPv6Enabled)) || ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIPv4Enabled && !isIPv6Enabled))) @@ -318,10 +320,9 @@ namespace MediaBrowser.Common.Net return true; } } - else if (hosts.Count <= 9) // 8 octets + port + else if (hosts.Count > 0 && hosts.Count <= 9) // 8 octets + port { - var splitSpan = host.Split('/'); - if (splitSpan.MoveNext() && IPAddress.TryParse(splitSpan.Current, out var address)) + if (IPAddress.TryParse(host.LeftPart('/'), out var address)) { addresses = new[] { address }; return true; diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 8b7df0470..77f18c544 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -203,12 +203,13 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - _ = nm.TryParseInterface(result, out IReadOnlyList? resultObj); - - // Check to see if dns resolution is working. If not, skip test. - _ = NetworkExtensions.TryParseHost(source, out var host); + // Check to see if DNS resolution is working. If not, skip test. + if (!NetworkExtensions.TryParseHost(source, out var host)) + { + return; + } - if (resultObj is not null && host.Length > 0) + if (nm.TryParseInterface(result, out var resultObj)) { result = resultObj.First().Address.ToString(); var intf = nm.GetBindAddress(source, out _); -- cgit v1.2.3 From 3f658515206a7ccea468de3fe9916e171de89b0d Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Mon, 3 Jul 2023 10:03:39 +0200 Subject: Apply review suggestions --- Jellyfin.Networking/Manager/NetworkManager.cs | 143 ++++++++++---------------- MediaBrowser.Common/Net/NetworkExtensions.cs | 14 +-- 2 files changed, 58 insertions(+), 99 deletions(-) (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs') diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 7d21c26cd..c80038e7d 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -590,35 +590,22 @@ namespace Jellyfin.Networking.Manager /// public bool TryParseInterface(string intf, [NotNullWhen(true)] out IReadOnlyList? result) { - var resultList = new List(); - if (string.IsNullOrEmpty(intf) || _interfaces is null) + if (string.IsNullOrEmpty(intf) + || _interfaces is null + || _interfaces.Count == 0) { - result = resultList.AsReadOnly(); + result = null; return false; } // Match all interfaces starting with names starting with token - var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf, StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index).ToList(); - if (matchedInterfaces.Count > 0) - { - _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); - - // Use interface IP instead of name - foreach (var iface in matchedInterfaces) - { - if ((IsIPv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) - || (IsIPv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) - { - resultList.Add(iface); - } - } - - result = resultList.AsReadOnly(); - return true; - } - - result = resultList.AsReadOnly(); - return false; + 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; } /// @@ -693,11 +680,7 @@ namespace Jellyfin.Networking.Manager if (individualInterfaces) { - foreach (var iface in _interfaces) - { - result.Add(iface); - } - + result.AddRange(_interfaces); return result; } @@ -792,37 +775,37 @@ namespace Jellyfin.Networking.Manager .ThenBy(x => x.Index) .ToList(); - if (availableInterfaces.Count > 0) + if (availableInterfaces.Count == 0) { - // If no source address is given, use the preferred (first) interface - if (source is null) - { - result = NetworkExtensions.FormatIPString(availableInterfaces.First().Address); - _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result); - return result; - } + // 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; + } + + // If no source address is given, use the preferred (first) interface + if (source is null) + { + result = NetworkExtensions.FormatIPString(availableInterfaces.First().Address); + _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result); + return result; + } - // 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) + // 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)) { - 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; - } + result = NetworkExtensions.FormatIPString(intf.Address); + _logger.LogDebug("{Source}: Found interface with matching subnet, using it as bind address: {Result}", source, result); + return result; } - - // 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; } - // 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); + // 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; } @@ -845,18 +828,13 @@ namespace Jellyfin.Networking.Manager if (NetworkExtensions.TryParseHost(address, out var addresses, IsIPv4Enabled, IsIPv6Enabled)) { - bool match = false; foreach (var ept in addresses) { - match = match || IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept))); - - if (match) + if (IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept)))) { - break; + return true; } } - - return match; } return false; @@ -881,33 +859,23 @@ namespace Jellyfin.Networking.Manager private bool CheckIfLanAndNotExcluded(IPAddress address) { - bool match = false; foreach (var lanSubnet in _lanSubnets) { - match = lanSubnet.Contains(address); - - if (match) + if (lanSubnet.Contains(address)) { - break; - } - } - - if (!match) - { - return match; - } - - foreach (var excludedSubnet in _excludedSubnets) - { - match = match && !excludedSubnet.Contains(address); + foreach (var excludedSubnet in _excludedSubnets) + { + if (excludedSubnet.Contains(address)) + { + return false; + } + } - if (!match) - { - break; + return true; } } - return match; + return false; } /// @@ -1017,14 +985,11 @@ namespace Jellyfin.Networking.Manager .OrderByDescending(x => x.Subnet.Contains(source)) .ThenBy(x => x.Index) .Select(x => x.Address) - .FirstOrDefault(); + .First(); - if (bindAddress is not null) - { - result = NetworkExtensions.FormatIPString(bindAddress); - _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result); - return true; - } + result = NetworkExtensions.FormatIPString(bindAddress); + _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result); + return true; } _logger.LogWarning("{Source}: External request received, no matching external bind address found, trying internal addresses.", source); @@ -1073,7 +1038,7 @@ namespace Jellyfin.Networking.Manager // (For systems with multiple network cards and/or multiple subnets) foreach (var intf in extResult) { - if (!IsInLocalNetwork(intf.Address) && intf.Subnet.Contains(source)) + if (intf.Subnet.Contains(source)) { result = NetworkExtensions.FormatIPString(intf.Address); _logger.LogDebug("{Source}: Found external interface with matching subnet, using it as bind address: {Result}", source, result); diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index ae85583a5..47475b3da 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -183,14 +183,8 @@ namespace MediaBrowser.Common.Net } } - if (tmpResult.Count > 0) - { - result = tmpResult; - return true; - } - - result = null; - return false; + result = tmpResult; + return tmpResult.Count > 0; } /// @@ -307,8 +301,8 @@ namespace MediaBrowser.Common.Net // Is an IP4 or IP4:port if (IPAddress.TryParse(hosts[0].AsSpan().LeftPart('/'), out var address)) { - if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIPv4Enabled && isIPv6Enabled)) || - ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIPv4Enabled && !isIPv6Enabled))) + if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIPv4Enabled && isIPv6Enabled)) + || ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIPv4Enabled && !isIPv6Enabled))) { addresses = Array.Empty(); return false; -- cgit v1.2.3