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/INetworkManager.cs | 128 ++++------------------------- 1 file changed, 15 insertions(+), 113 deletions(-) (limited to 'MediaBrowser.Common/Net/INetworkManager.cs') diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index b93939730..fdf42bdbc 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -18,44 +18,29 @@ namespace MediaBrowser.Common.Net event EventHandler NetworkChanged; /// - /// Gets the published server urls list. + /// Gets a value indicating whether iP6 is enabled. /// - Dictionary PublishedServerUrls { get; } + bool IsIpv6Enabled { get; } /// - /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. + /// Gets a value indicating whether iP4 is enabled. /// - bool TrustAllIP6Interfaces { get; } - - /// - /// Gets the remote address filter. - /// - Collection RemoteAddressFilter { get; } - - /// - /// Gets or sets a value indicating whether iP6 is enabled. - /// - bool IsIP6Enabled { get; set; } - - /// - /// Gets or sets a value indicating whether iP4 is enabled. - /// - bool IsIP4Enabled { get; set; } + bool IsIpv4Enabled { get; } /// /// Calculates the list of interfaces to use for Kestrel. /// - /// A Collection{IPObject} object containing all the interfaces to bind. + /// A List{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. - Collection GetAllBindInterfaces(bool individualInterfaces = false); + List GetAllBindInterfaces(bool individualInterfaces = false); /// /// Returns a collection containing the loopback interfaces. /// - /// Collection{IPObject}. - Collection GetLoopbacks(); + /// List{IPData}. + List GetLoopbacks(); /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) @@ -86,22 +71,12 @@ namespace MediaBrowser.Common.Net /// Source of the request. /// Optional port returned, if it's part of an override. /// IP Address to use, or loopback address if all else fails. - string GetBindInterface(IPObject source, out int? port); - - /// - /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) - /// If no bind addresses are specified, an internal interface address is selected. - /// (See . - /// - /// Source of the request. - /// Optional port returned, if it's part of an override. - /// IP Address to use, or loopback address if all else fails. string GetBindInterface(HttpRequest source, out int? port); /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . + /// (See . /// /// IP address of the request. /// Optional port returned, if it's part of an override. @@ -111,48 +86,19 @@ namespace MediaBrowser.Common.Net /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . + /// (See . /// /// Source of the request. /// Optional port returned, if it's part of an override. /// IP Address to use, or loopback address if all else fails. string GetBindInterface(string source, out int? port); - /// - /// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses. - /// - /// IP address to check. - /// True if it is. - bool IsExcludedInterface(IPAddress address); - /// /// Get a list of all the MAC addresses associated with active interfaces. /// /// List of MAC addresses. IReadOnlyCollection GetMacAddresses(); - /// - /// Checks to see if the IP Address provided matches an interface that has a gateway. - /// - /// IP to check. Can be an IPAddress or an IPObject. - /// Result of the check. - bool IsGatewayInterface(IPObject? addressObj); - - /// - /// Checks to see if the IP Address provided matches an interface that has a gateway. - /// - /// IP to check. Can be an IPAddress or an IPObject. - /// Result of the check. - bool IsGatewayInterface(IPAddress? addressObj); - - /// - /// Returns true if the address is a private address. - /// The configuration option TrustIP6Interfaces overrides this functions behaviour. - /// - /// Address to check. - /// True or False. - bool IsPrivateAddressRange(IPObject address); - /// /// Returns true if the address is part of the user defined LAN. /// The configuration option TrustIP6Interfaces overrides this functions behaviour. @@ -161,14 +107,6 @@ namespace MediaBrowser.Common.Net /// True if endpoint is within the LAN range. bool IsInLocalNetwork(string address); - /// - /// Returns true if the address is part of the user defined LAN. - /// The configuration option TrustIP6Interfaces overrides this functions behaviour. - /// - /// IP to check. - /// True if endpoint is within the LAN range. - bool IsInLocalNetwork(IPObject address); - /// /// Returns true if the address is part of the user defined LAN. /// The configuration option TrustIP6Interfaces overrides this functions behaviour. @@ -178,55 +116,19 @@ namespace MediaBrowser.Common.Net bool IsInLocalNetwork(IPAddress address); /// - /// Attempts to convert the token to an IP address, permitting for interface descriptions and indexes. - /// eg. "eth1", or "TP-LINK Wireless USB Adapter". + /// Attempts to convert the interface name to an IP address. + /// eg. "eth1", or "enp3s5". /// - /// Token to parse. + /// Interface name. /// Resultant object's ip addresses, if successful. /// Success of the operation. - bool TryParseInterface(string token, out Collection? result); - - /// - /// Parses an array of strings into a Collection{IPObject}. - /// - /// Values to parse. - /// When true, only include values beginning with !. When false, ignore ! values. - /// IPCollection object containing the value strings. - Collection CreateIPCollection(string[] values, bool negated = false); + bool TryParseInterface(string intf, out Collection? result); /// /// Returns all the internal Bind interface addresses. /// /// An internal list of interfaces addresses. - Collection GetInternalBindAddresses(); - - /// - /// Checks to see if an IP address is still a valid interface address. - /// - /// IP address to check. - /// True if it is. - bool IsValidInterfaceAddress(IPAddress address); - - /// - /// Returns true if the IP address is in the excluded list. - /// - /// IP to check. - /// True if excluded. - bool IsExcluded(IPAddress ip); - - /// - /// Returns true if the IP address is in the excluded list. - /// - /// IP to check. - /// True if excluded. - bool IsExcluded(EndPoint ip); - - /// - /// Gets the filtered LAN ip addresses. - /// - /// Optional filter for the list. - /// Returns a filtered list of LAN addresses. - Collection GetFilteredLANSubnets(Collection? filter = null); + List GetInternalBindAddresses(); /// /// Checks to see if has access. -- cgit v1.2.3 From 997aa3f1e74d6bbe4f9f928e1162638d75feb12e Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Tue, 19 Jul 2022 21:53:10 +0200 Subject: Fix build --- Jellyfin.Networking/Manager/NetworkManager.cs | 14 +++++++------- MediaBrowser.Common/Net/INetworkManager.cs | 4 ++-- tests/Jellyfin.Networking.Tests/NetworkParseTests.cs | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) (limited to 'MediaBrowser.Common/Net/INetworkManager.cs') diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index f51fd85dd..d9ef2c6a4 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -241,7 +241,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.ToLower(CultureInfo.InvariantCulture); + interfaceObject.Name = adapter.Name.ToLowerInvariant(); _interfaces.Add(interfaceObject); } @@ -249,7 +249,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.ToLower(CultureInfo.InvariantCulture); + interfaceObject.Name = adapter.Name.ToLowerInvariant(); _interfaces.Add(interfaceObject); } @@ -381,7 +381,7 @@ namespace Jellyfin.Networking.Manager if (config.IgnoreVirtualInterfaces) { // Remove potentially exisiting * and split config string into prefixes - var virtualInterfacePrefixes = config.VirtualInterfaceNames.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase).ToLower().Split(','); + var virtualInterfacePrefixes = config.VirtualInterfaceNames.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase).ToLowerInvariant().Split(','); // Check all interfaces for matches against the prefixes and add the interface IPs to _bindExclusions if (_bindAddresses.Count > 0 && virtualInterfacePrefixes.Length > 0) @@ -419,10 +419,10 @@ 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); + _ = 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)); + var ips = remoteIPFilter.Where(x => !x.Contains('/', StringComparison.OrdinalIgnoreCase)); foreach (var ip in ips) { if (IPAddress.TryParse(ip, out var ipp)) @@ -573,7 +573,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.ToLower(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase)); + var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf.ToLowerInvariant(), StringComparison.OrdinalIgnoreCase)); if (matchedInterfaces.Any()) { _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); @@ -998,7 +998,7 @@ namespace Jellyfin.Networking.Manager 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.Distinct(); + validPublishedServerUrls = validPublishedServerUrls.GroupBy(x => x.Key).Select(y => y.First()).ToList(); // Check for user override. foreach (var data in validPublishedServerUrls) diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index fdf42bdbc..9f4853557 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -18,12 +18,12 @@ namespace MediaBrowser.Common.Net event EventHandler NetworkChanged; /// - /// Gets a value indicating whether iP6 is enabled. + /// Gets a value indicating whether IPv6 is enabled. /// bool IsIpv6Enabled { get; } /// - /// Gets a value indicating whether iP4 is enabled. + /// Gets a value indicating whether IPv4 is enabled. /// bool IsIpv4Enabled { get; } diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index ce638c913..d451fbaef 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -58,7 +58,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - Assert.Equal(value, "[" + String.Join(",", nm.GetInternalBindAddresses().Select(x => x.Address + "/" + x.Subnet.PrefixLength)) + "]"); + Assert.Equal(value, "[" + string.Join(",", nm.GetInternalBindAddresses().Select(x => x.Address + "/" + x.Subnet.PrefixLength)) + "]"); } [Theory] -- 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/INetworkManager.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 2d3a16ad0f814c4e26a741744b8fc7f3c31890dc Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Wed, 20 Jul 2022 21:19:35 +0200 Subject: Simplify code --- Jellyfin.Networking/Manager/NetworkManager.cs | 267 +++++++------------------- MediaBrowser.Common/Net/INetworkManager.cs | 2 +- 2 files changed, 72 insertions(+), 197 deletions(-) (limited to 'MediaBrowser.Common/Net/INetworkManager.cs') diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 757b5994b..50fc97461 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -25,11 +25,6 @@ namespace Jellyfin.Networking.Manager /// private readonly object _initLock; - /// - /// Dictionary containing interface addresses and their subnets. - /// - private readonly List _interfaces; - /// /// List of all interface MAC addresses. /// @@ -53,6 +48,11 @@ namespace Jellyfin.Networking.Manager /// private bool _eventfire; + /// + /// Dictionary containing interface addresses and their subnets. + /// + private List _interfaces; + /// /// Unfiltered user defined LAN subnets () /// or internal interface network subnets if undefined by user. @@ -64,16 +64,6 @@ namespace Jellyfin.Networking.Manager /// private List _excludedSubnets; - /// - /// List of interfaces to bind to. - /// - private List _bindAddresses; - - /// - /// List of interface addresses to exclude from bind. - /// - private List _bindExclusions; - /// /// True if this object is disposed. /// @@ -190,9 +180,10 @@ namespace Jellyfin.Networking.Manager try { await Task.Delay(2000).ConfigureAwait(false); + var networkConfig = _configurationManager.GetNetworkConfiguration(); + InitialiseLan(networkConfig); InitialiseInterfaces(); - // Recalculate LAN caches. - InitialiseLan(_configurationManager.GetNetworkConfiguration()); + EnforceBindRestrictions(networkConfig); NetworkChanged?.Invoke(this, EventArgs.Empty); } @@ -217,7 +208,7 @@ namespace Jellyfin.Networking.Manager try { - IEnumerable nics = NetworkInterface.GetAllNetworkInterfaces() + var nics = NetworkInterface.GetAllNetworkInterfaces() .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up); foreach (NetworkInterface adapter in nics) @@ -270,33 +261,7 @@ namespace Jellyfin.Networking.Manager _logger.LogError(ex, "Error obtaining interfaces."); } - // If for some reason we don't have an interface info, resolve the DNS name. - if (_interfaces.Count == 0) - { - _logger.LogError("No interfaces information available. Resolving DNS name."); - var hostName = Dns.GetHostName(); - if (Uri.CheckHostName(hostName).Equals(UriHostNameType.Dns)) - { - try - { - IPHostEntry hip = Dns.GetHostEntry(hostName); - foreach (var address in hip.AddressList) - { - _interfaces.Add(new IPData(address, null)); - } - } - catch (SocketException ex) - { - // Log and then ignore socket errors, as the result value will just be an empty array. - _logger.LogWarning("GetHostEntryAsync failed with {Message}.", ex.Message); - } - } - - if (_interfaces.Count == 0) - { - _logger.LogWarning("No interfaces information available. Using loopback."); - } - } + _logger.LogWarning("No interfaces information available. Using loopback."); if (IsIpv4Enabled && !IsIpv6Enabled) { @@ -354,55 +319,46 @@ namespace Jellyfin.Networking.Manager } /// - /// Initialises the network bind addresses. + /// Enforce bind addresses and exclusions on available interfaces. /// - private void InitialiseBind(NetworkConfiguration config) + private void EnforceBindRestrictions(NetworkConfiguration config) { lock (_initLock) { - // Use explicit bind addresses - if (config.LocalNetworkAddresses.Length > 0) + // Respect explicit bind addresses + var localNetworkAddresses = config.LocalNetworkAddresses; + if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses.First())) { - _bindAddresses = config.LocalNetworkAddresses.Select(p => IPAddress.TryParse(p, out var addresses) + var 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); + : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)) + .Select(x => x.Address) + .FirstOrDefault() ?? IPAddress.None)) + .ToList(); + bindAddresses.RemoveAll(x => x == IPAddress.None); + _interfaces = _interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList(); } - else - { - // Use all addresses from all interfaces - _bindAddresses = _interfaces.Select(x => x.Address).ToList(); - } - - _bindExclusions = new List(); - // Add all interfaces matching any virtual machine interface prefix to _bindExclusions + // Remove all interfaces matching any virtual machine interface prefix if (config.IgnoreVirtualInterfaces) { // Remove potentially exisiting * and split config string into prefixes - var virtualInterfacePrefixes = config.VirtualInterfaceNames.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase).ToLowerInvariant().Split(','); + var virtualInterfacePrefixes = config.VirtualInterfaceNames + .Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase) + .ToLowerInvariant() + .Split(','); - // Check all interfaces for matches against the prefixes and add the interface IPs to _bindExclusions - if (_bindAddresses.Count > 0 && virtualInterfacePrefixes.Length > 0) + // Check all interfaces for matches against the prefixes and remove them + if (_interfaces.Count > 0 && virtualInterfacePrefixes.Length > 0) { - var localInterfaces = _interfaces.ToList(); foreach (var virtualInterfacePrefix in virtualInterfacePrefixes) { - var excludedInterfaceIps = localInterfaces.Where(intf => intf.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase)) - .Select(intf => intf.Address); - foreach (var interfaceIp in excludedInterfaceIps) - { - _bindExclusions.Add(interfaceIp); - } + _interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase)); } } } - // Remove all excluded addresses from _bindAddresses - _bindAddresses.RemoveAll(x => _bindExclusions.Contains(x)); - - _logger.LogInformation("Using bind addresses: {0}", _bindAddresses); - _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions); + _logger.LogInformation("Using bind addresses: {0}", _interfaces.Select(x => x.Address)); } } @@ -477,7 +433,7 @@ namespace Jellyfin.Networking.Manager _publishedServerUrls[data] = replacement; } - else if (TryParseInterface(parts[0], out var ifaces)) + else if (TryParseInterface(ipParts[0], out var ifaces)) { foreach (var iface in ifaces) { @@ -509,6 +465,9 @@ namespace Jellyfin.Networking.Manager { NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); + InitialiseLan(config); + InitialiseRemote(config); + if (string.IsNullOrEmpty(MockNetworkSettings)) { InitialiseInterfaces(); @@ -533,9 +492,7 @@ namespace Jellyfin.Networking.Manager } } - InitialiseLan(config); - InitialiseBind(config); - InitialiseRemote(config); + EnforceBindRestrictions(config); InitialiseOverrides(config); } @@ -649,19 +606,8 @@ namespace Jellyfin.Networking.Manager /// public IReadOnlyList GetAllBindInterfaces(bool individualInterfaces = false) { - if (_bindAddresses.Count == 0) + if (_interfaces.Count == 0) { - if (_bindExclusions.Count > 0) - { - foreach (var exclusion in _bindExclusions) - { - // Return all the interfaces except the ones specifically excluded. - _interfaces.RemoveAll(intf => intf.Address == exclusion); - } - - return _interfaces; - } - // No bind address and no exclusions, so listen on all interfaces. var result = new List(); @@ -699,14 +645,7 @@ namespace Jellyfin.Networking.Manager return result; } - // Remove any excluded bind interfaces. - foreach (var exclusion in _bindExclusions) - { - // Return all the interfaces except the ones specifically excluded. - _bindAddresses.Remove(exclusion); - } - - return _bindAddresses.Select(s => new IPData(s, null)).ToList(); + return _interfaces; } /// @@ -770,8 +709,7 @@ namespace Jellyfin.Networking.Manager // Get the first LAN interface address that's not excluded and not a loopback address. var availableInterfaces = _interfaces.Where(x => !IPAddress.IsLoopback(x.Address)) - .OrderByDescending(x => _bindAddresses.Contains(x.Address)) - .ThenByDescending(x => IsInLocalNetwork(x.Address)) + .OrderByDescending(x => IsInLocalNetwork(x.Address)) .ThenBy(x => x.Index); if (availableInterfaces.Any()) @@ -815,21 +753,8 @@ namespace Jellyfin.Networking.Manager /// public IReadOnlyList GetInternalBindAddresses() { - if (_bindAddresses.Count == 0) - { - if (_bindExclusions.Count > 0) - { - // Return all the internal interfaces except the ones excluded. - return _interfaces.Where(p => !_bindExclusions.Contains(p.Address)).ToList(); - } - - // No bind address, so return all internal interfaces. - return _interfaces; - } - // Select all local bind addresses - return _interfaces.Where(x => _bindAddresses.Contains(x.Address)) - .Where(x => IsInLocalNetwork(x.Address)) + return _interfaces.Where(x => IsInLocalNetwork(x.Address)) .OrderBy(x => x.Index) .ToList(); } @@ -876,31 +801,6 @@ namespace Jellyfin.Networking.Manager return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback) || match; } - private IPData? FindInterfaceForIp(IPAddress address, bool localNetwork = false) - { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } - - var interfaces = _interfaces; - - if (localNetwork) - { - interfaces = interfaces.Where(x => IsInLocalNetwork(x.Address)).ToList(); - } - - foreach (var intf in interfaces) - { - if (intf.Subnet.Contains(address)) - { - return intf; - } - } - - return null; - } - private bool CheckIfLanAndNotExcluded(IPAddress address) { bool match = false; @@ -992,79 +892,54 @@ namespace Jellyfin.Networking.Manager { result = string.Empty; - int count = _bindAddresses.Count; - if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any))) + int count = _interfaces.Count(); + if (count == 1 && (_interfaces[0].Equals(IPAddress.Any) || _interfaces[0].Equals(IPAddress.IPv6Any))) { // Ignore IPAny addresses. count = 0; } - if (count != 0) + if (count > 0) { - // Check to see if any of the bind interfaces are in the same subnet as the source. - IPAddress? defaultGateway = null; IPAddress? bindAddress = null; + var externalInterfaces = _interfaces.Where(x => !IsInLocalNetwork(x.Address)) + .OrderBy(x => x.Index) + .ToList(); - if (isInExternalSubnet) + if (isInExternalSubnet && externalInterfaces.Any()) { - // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first. - foreach (var addr in _bindAddresses) - { - if (defaultGateway == null && !IsInLocalNetwork(addr)) - { - defaultGateway = addr; - } - - var intf = _interfaces.Where(x => x.Subnet.Contains(addr)).OrderBy(x => x.Index).FirstOrDefault(); + // Check to see if any of the external bind interfaces are in the same subnet as the source. + // If none exists, this will select the first external interface if there is one. + bindAddress = externalInterfaces + .OrderByDescending(x => x.Subnet.Contains(source)) + .ThenBy(x => x.Index) + .Select(x => x.Address) + .FirstOrDefault(); - if (bindAddress == null && intf != null && intf.Subnet.Contains(source)) - { - bindAddress = intf.Address; - } - - if (defaultGateway != null && bindAddress != null) - { - break; - } + if (bindAddress != null) + { + result = NetworkExtensions.FormatIpString(bindAddress); + _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching external bind interface. {Result}", source, result); + return true; } } else { - // Look for the best internal address. - foreach (var bA in _bindAddresses.Where(x => IsInLocalNetwork(x))) + // Check to see if any of the internal bind interfaces are in the same subnet as the source. + // If none exists, this will select the first internal interface if there is one. + bindAddress = _interfaces.Where(x => IsInLocalNetwork(x.Address)) + .OrderByDescending(x => x.Subnet.Contains(source)) + .ThenBy(x => x.Index) + .Select(x => x.Address) + .FirstOrDefault(); + + if (bindAddress != null) { - var intf = FindInterfaceForIp(source, true); - if (intf != null) - { - bindAddress = intf.Address; - break; - } + result = NetworkExtensions.FormatIpString(bindAddress); + _logger.LogWarning("{Source}: External request received, only an internal interface bind found. {Result}", source, result); + return true; } } - - if (bindAddress != null) - { - result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching bind interface subnet. {Result}", source, result); - return true; - } - - if (isInExternalSubnet && defaultGateway != null) - { - result = NetworkExtensions.FormatIpString(defaultGateway); - _logger.LogDebug("{Source}: GetBindInterface: Using first user defined external interface. {Result}", source, result); - return true; - } - - result = NetworkExtensions.FormatIpString(_bindAddresses[0]); - _logger.LogDebug("{Source}: GetBindInterface: Selected first user defined interface. {Result}", source, result); - - if (isInExternalSubnet) - { - _logger.LogWarning("{Source}: External request received, only an internal interface bind found.", source); - } - - return true; } return false; diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index bb0e2dcb3..21ff98237 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -124,7 +124,7 @@ namespace MediaBrowser.Common.Net bool TryParseInterface(string intf, out List? result); /// - /// Returns all the internal Bind interface addresses. + /// Returns all the internal bind interface addresses. /// /// An internal list of interfaces addresses. IReadOnlyList GetInternalBindAddresses(); -- cgit v1.2.3 From 59a86568d9539245dee30cf3a33ef6beb31f4bba Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 21 Jul 2022 22:09:54 +0200 Subject: Cleanup and fixes --- Jellyfin.Networking/Manager/NetworkManager.cs | 12 +++++-- .../Extensions/ApiServiceCollectionExtensions.cs | 8 ++--- MediaBrowser.Common/Net/INetworkManager.cs | 42 +++++++++++----------- MediaBrowser.Common/Net/IPData.cs | 8 ++--- MediaBrowser.Model/Net/ISocketFactory.cs | 1 - RSSDP/SsdpCommunicationsServer.cs | 6 +--- 6 files changed, 39 insertions(+), 38 deletions(-) (limited to 'MediaBrowser.Common/Net/INetworkManager.cs') diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 12edb0e55..0f8f1a36a 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -263,7 +263,7 @@ namespace Jellyfin.Networking.Manager if (_interfaces.Count == 0) { - _logger.LogWarning("No interfaces information available. Using loopback."); + _logger.LogWarning("No interface information available. Using loopback interface(s)."); if (IsIpv4Enabled && !IsIpv6Enabled) { @@ -450,6 +450,14 @@ namespace Jellyfin.Networking.Manager _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)) + { + foreach (var lan in _lanSubnets) + { + var lanPrefix = lan.Prefix; + _publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement; + } + } else if (IPAddress.TryParse(ipParts[0], out IPAddress? result)) { var data = new IPData(result, null); @@ -469,7 +477,7 @@ namespace Jellyfin.Networking.Manager } else { - _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]); + _logger.LogError("Unable to parse bind override: {Entry}", entry); } } } diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index a393b80db..25516271c 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -350,14 +350,14 @@ namespace Jellyfin.Server.Extensions } else if (NetworkExtensions.TryParseSubnets(new[] { allowedProxies[i] }, out var subnets)) { - for (var j = 0; j < subnets.Count; j++) + foreach (var subnet in subnets) { - AddIpAddress(config, options, subnets[j].Prefix, subnets[j].PrefixLength); + AddIpAddress(config, options, subnet.Prefix, subnet.PrefixLength); } } - else if (NetworkExtensions.TryParseHost(allowedProxies[i], out var host)) + else if (NetworkExtensions.TryParseHost(allowedProxies[i], out var addresses)) { - foreach (var address in host) + foreach (var address in addresses) { AddIpAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 21ff98237..d462e954a 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -17,14 +17,14 @@ namespace MediaBrowser.Common.Net event EventHandler NetworkChanged; /// - /// Gets a value indicating whether IPv6 is enabled. + /// Gets a value indicating whether IPv4 is enabled. /// - bool IsIpv6Enabled { get; } + bool IsIpv4Enabled { get; } /// - /// Gets a value indicating whether IPv4 is enabled. + /// Gets a value indicating whether IPv6 is enabled. /// - bool IsIpv4Enabled { get; } + bool IsIpv6Enabled { get; } /// /// Calculates the list of interfaces to use for Kestrel. @@ -42,7 +42,7 @@ namespace MediaBrowser.Common.Net IReadOnlyList GetLoopbacks(); /// - /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. /// The priority of selection is as follows:- /// @@ -56,40 +56,40 @@ namespace MediaBrowser.Common.Net /// /// If the source is from a public subnet address range and the user hasn't specified any bind addresses:- /// The first public interface that isn't a loopback and contains the source subnet. - /// The first public interface that isn't a loopback. Priority is given to interfaces with gateways. - /// An internal interface if there are no public ip addresses. + /// The first public interface that isn't a loopback. + /// The first internal interface that isn't a loopback. /// /// If the source is from a private subnet address range and the user hasn't specified any bind addresses:- /// The first private interface that contains the source subnet. - /// The first private interface that isn't a loopback. Priority is given to interfaces with gateways. + /// The first private interface that isn't a loopback. /// /// If no interfaces meet any of these criteria, then a loopback address is returned. /// - /// Interface that have been specifically excluded from binding are not used in any of the calculations. + /// Interfaces that have been specifically excluded from binding are not used in any of the calculations. /// /// Source of the request. /// Optional port returned, if it's part of an override. - /// IP Address to use, or loopback address if all else fails. + /// IP address to use, or loopback address if all else fails. string GetBindInterface(HttpRequest source, out int? port); /// - /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. /// (See . /// /// IP address of the request. /// Optional port returned, if it's part of an override. - /// IP Address to use, or loopback address if all else fails. + /// IP address to use, or loopback address if all else fails. string GetBindInterface(IPAddress source, out int? port); /// - /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) + /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. /// (See . /// /// Source of the request. /// Optional port returned, if it's part of an override. - /// IP Address to use, or loopback address if all else fails. + /// IP address to use, or loopback address if all else fails. string GetBindInterface(string source, out int? port); /// @@ -100,7 +100,6 @@ namespace MediaBrowser.Common.Net /// /// Returns true if the address is part of the user defined LAN. - /// The configuration option TrustIP6Interfaces overrides this functions behaviour. /// /// IP to check. /// True if endpoint is within the LAN range. @@ -108,7 +107,6 @@ namespace MediaBrowser.Common.Net /// /// Returns true if the address is part of the user defined LAN. - /// The configuration option TrustIP6Interfaces overrides this functions behaviour. /// /// IP to check. /// True if endpoint is within the LAN range. @@ -119,21 +117,21 @@ namespace MediaBrowser.Common.Net /// eg. "eth1", or "enp3s5". /// /// Interface name. - /// Resultant object's ip addresses, if successful. + /// Resulting object's IP addresses, if successful. /// Success of the operation. bool TryParseInterface(string intf, out List? result); /// - /// Returns all the internal bind interface addresses. + /// Returns all internal (LAN) bind interface addresses. /// - /// An internal list of interfaces addresses. + /// An list of internal (LAN) interfaces addresses. IReadOnlyList GetInternalBindAddresses(); /// - /// Checks to see if has access. + /// Checks if has access to the server. /// - /// IP Address of client. - /// True if has access, otherwise false. + /// IP address of the client. + /// True if it has access, otherwise false. bool HasRemoteAccess(IPAddress remoteIp); } } diff --git a/MediaBrowser.Common/Net/IPData.cs b/MediaBrowser.Common/Net/IPData.cs index 6901d6ad8..384efe8f6 100644 --- a/MediaBrowser.Common/Net/IPData.cs +++ b/MediaBrowser.Common/Net/IPData.cs @@ -12,9 +12,9 @@ namespace MediaBrowser.Common.Net /// /// Initializes a new instance of the class. /// - /// An . + /// The . /// The . - /// The object's name. + /// The interface name. public IPData(IPAddress address, IPNetwork? subnet, string name) { Address = address; @@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Net /// /// Initializes a new instance of the class. /// - /// An . + /// The . /// The . public IPData(IPAddress address, IPNetwork? subnet) : this(address, subnet, string.Empty) @@ -53,7 +53,7 @@ namespace MediaBrowser.Common.Net public string Name { get; set; } /// - /// Gets the AddressFamily of this object. + /// Gets the AddressFamily of the object. /// public AddressFamily AddressFamily { diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs index e5cf7adbc..f3bc31796 100644 --- a/MediaBrowser.Model/Net/ISocketFactory.cs +++ b/MediaBrowser.Model/Net/ISocketFactory.cs @@ -1,6 +1,5 @@ #pragma warning disable CS1591 -using System.Collections.Generic; using System.Net; namespace MediaBrowser.Model.Net diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index e6c0a4403..92c9c83c0 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -142,11 +142,7 @@ namespace Rssdp.Infrastructure if (_BroadcastListenSockets != null) { _logger.LogInformation("{0} disposing _BroadcastListenSocket", GetType().Name); - foreach (var socket in _BroadcastListenSockets) - { - socket.Dispose(); - } - + _BroadcastListenSockets.ForEach(s => s.Dispose()); _BroadcastListenSockets = null; } } -- cgit v1.2.3 From 26d79a5ce3639700131d0359c60c096cd0fbb093 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Sat, 15 Oct 2022 20:57:02 +0200 Subject: Properly name some bind address functions, cleanup logging --- Emby.Server.Implementations/ApplicationHost.cs | 4 +- .../EntryPoints/UdpServerEntryPoint.cs | 2 +- Jellyfin.Networking/Manager/NetworkManager.cs | 47 +++++++++++----------- MediaBrowser.Common/Net/INetworkManager.cs | 6 +-- 4 files changed, 29 insertions(+), 30 deletions(-) (limited to 'MediaBrowser.Common/Net/INetworkManager.cs') diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 2ca5e6ded..7004af3d4 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1069,7 +1069,7 @@ namespace Emby.Server.Implementations return PublishedServerUrl.Trim('/'); } - string smart = NetManager.GetBindInterface(remoteAddr, out var port); + string smart = NetManager.GetBindAddress(remoteAddr, out var port); return GetLocalApiUrl(smart.Trim('/'), null, port); } @@ -1118,7 +1118,7 @@ namespace Emby.Server.Implementations public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true) { // With an empty source, the port will be null - var smart = NetManager.GetBindInterface(ipAddress, out _); + var smart = NetManager.GetBindAddress(ipAddress, out _); var scheme = !allowHttps ? Uri.UriSchemeHttp : null; int? port = !allowHttps ? HttpPort : null; return GetLocalApiUrl(smart, scheme, port); diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index 01a987b6a..c2ffaf1bd 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -92,7 +92,7 @@ namespace Emby.Server.Implementations.EntryPoints } var broadcastAddress = NetworkExtensions.GetBroadcastAddress(bindAddress.Subnet); - _logger.LogDebug("Binding UDP server to {Address}", broadcastAddress.ToString()); + _logger.LogDebug("Binding UDP server to {Address} on port {PortNumber}", broadcastAddress.ToString(), PortNumber); _udpServers.Add(new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber)); } diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 3c347461a..7e9fb4df7 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -6,7 +6,6 @@ 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; using MediaBrowser.Common.Net; @@ -280,7 +279,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.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString())); } } @@ -320,8 +319,8 @@ namespace Jellyfin.Networking.Manager } } - _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("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)); } } @@ -386,7 +385,7 @@ namespace Jellyfin.Networking.Manager _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); } - _logger.LogInformation("Using bind addresses: {0}", _interfaces.Select(x => x.Address)); + _logger.LogInformation("Using bind addresses: {0}", _interfaces.OrderByDescending(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.Address)); } } @@ -691,7 +690,7 @@ namespace Jellyfin.Networking.Manager public string GetBindInterface(string source, out int? port) { _ = NetworkExtensions.TryParseHost(source, out var address, IsIpv4Enabled, IsIpv6Enabled); - var result = GetBindInterface(address.FirstOrDefault(), out port); + var result = GetBindAddress(address.FirstOrDefault(), out port); return result; } @@ -700,14 +699,14 @@ namespace Jellyfin.Networking.Manager { string result; _ = NetworkExtensions.TryParseHost(source.Host.Host, out var addresses, IsIpv4Enabled, IsIpv6Enabled); - result = GetBindInterface(addresses.FirstOrDefault(), out port); + result = GetBindAddress(addresses.FirstOrDefault(), out port); port ??= source.Host.Port; return result; } /// - public string GetBindInterface(IPAddress? source, out int? port) + public string GetBindAddress(IPAddress? source, out int? port) { port = null; @@ -726,7 +725,7 @@ namespace Jellyfin.Networking.Manager } bool isExternal = !_lanSubnets.Any(network => network.Contains(source)); - _logger.LogDebug("GetBindInterface with source {Source}. External: {IsExternal}:", source, isExternal); + _logger.LogDebug("Trying to get bind address for source {Source} - External: {IsExternal}", source, isExternal); if (MatchesPublishedServerUrl(source, isExternal, out result)) { @@ -759,7 +758,7 @@ namespace Jellyfin.Networking.Manager if (intf.Address.Equals(source)) { result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface: {Result}", source, result); + _logger.LogDebug("{Source}: Found matching interface to use as bind address: {Result}", source, result); return result; } } @@ -771,20 +770,20 @@ namespace Jellyfin.Networking.Manager if (intf.Subnet.Contains(source)) { result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range: {Result}", source, result); + _logger.LogDebug("{Source}: Found internal interface with matching subnet, using it as bind address: {Result}", source, result); return result; } } } result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address); - _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface: {Result}", source, result); + _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}: GetBindInterface: Loopback {Result} returned.", source, result); + _logger.LogWarning("{Source}: Only loopback {Result} returned, using that as bind address.", source, result); return result; } @@ -897,7 +896,7 @@ namespace Jellyfin.Networking.Manager if (string.IsNullOrEmpty(bindPreference)) { - _logger.LogInformation("{Source}: No matching bind address override found", source); + _logger.LogDebug("{Source}: No matching bind address override found.", source); return false; } @@ -914,18 +913,18 @@ namespace Jellyfin.Networking.Manager if (port != null) { - _logger.LogInformation("{Source}: Matching bind address override found {Address}:{Port}", source, bindPreference, port); + _logger.LogDebug("{Source}: Matching bind address override found: {Address}:{Port}", source, bindPreference, port); } else { - _logger.LogInformation("{Source}: Matching bind address override found {Address}", source, bindPreference); + _logger.LogDebug("{Source}: Matching bind address override found: {Address}", source, bindPreference); } return true; } /// - /// Attempts to match the source against a user defined bind interface. + /// Attempts to match the source against the user defined bind interfaces. /// /// IP source address to use. /// True if the source is in the external subnet. @@ -964,12 +963,12 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: External request received, matching external bind interface found: {Result}", source, result); + _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 interface found, trying internal interfaces.", source); + _logger.LogWarning("{Source}: External request received, no matching external bind address found, trying internal addresses.", source); } else { @@ -984,7 +983,7 @@ namespace Jellyfin.Networking.Manager if (bindAddress != null) { result = NetworkExtensions.FormatIpString(bindAddress); - _logger.LogDebug("{Source}: Internal request received, matching internal bind interface found: {Result}", source, result); + _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result); return true; } } @@ -994,7 +993,7 @@ namespace Jellyfin.Networking.Manager } /// - /// Attempts to match the source against an external interface. + /// Attempts to match the source against external interfaces. /// /// IP source address to use. /// The result, if a match is found. @@ -1014,7 +1013,7 @@ namespace Jellyfin.Networking.Manager if (!IsInLocalNetwork(intf.Address) && intf.Subnet.Contains(source)) { result = NetworkExtensions.FormatIpString(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range: {Result}", source, result); + _logger.LogDebug("{Source}: Found external interface with matching subnet, using it as bind address: {Result}", source, result); return true; } } @@ -1022,11 +1021,11 @@ namespace Jellyfin.Networking.Manager if (hasResult != null) { result = NetworkExtensions.FormatIpString(hasResult); - _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface: {Result}", source, result); + _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result); return true; } - _logger.LogDebug("{Source}: External request received, but no WAN interface found. Need to route through internal network.", source); + _logger.LogWarning("{Source}: External request received, but no external interface found. Need to route through internal network.", source); return false; } } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index d462e954a..f0f16af78 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -75,17 +75,17 @@ namespace MediaBrowser.Common.Net /// /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . + /// (See . /// /// IP address of the request. /// Optional port returned, if it's part of an override. /// IP address to use, or loopback address if all else fails. - string GetBindInterface(IPAddress source, out int? port); + string GetBindAddress(IPAddress source, out int? port); /// /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . + /// (See . /// /// Source of the request. /// Optional port returned, if it's part of an override. -- 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/INetworkManager.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 42498194d9a4069b8cdeb9446f2714f74e3169de Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Thu, 16 Feb 2023 18:15:12 +0100 Subject: Replace ISocket and UdpSocket, fix DLNA and SSDP binding and discovery --- Emby.Dlna/Configuration/DlnaOptions.cs | 2 +- Emby.Dlna/Main/DlnaEntryPoint.cs | 47 ++-- Emby.Dlna/Ssdp/DeviceDiscovery.cs | 6 +- Emby.Server.Implementations/ApplicationHost.cs | 4 +- .../EntryPoints/UdpServerEntryPoint.cs | 34 +-- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 10 +- Emby.Server.Implementations/Net/SocketFactory.cs | 69 +++--- Emby.Server.Implementations/Net/UdpSocket.cs | 267 --------------------- Jellyfin.Networking/Manager/NetworkManager.cs | 11 +- .../Extensions/WebHostBuilderExtensions.cs | 2 +- MediaBrowser.Common/Net/INetworkManager.cs | 12 +- MediaBrowser.Common/Net/IPData.cs | 75 ------ MediaBrowser.Model/MediaBrowser.Model.csproj | 1 + MediaBrowser.Model/Net/IPData.cs | 75 ++++++ MediaBrowser.Model/Net/ISocket.cs | 34 --- MediaBrowser.Model/Net/ISocketFactory.cs | 24 +- RSSDP/ISsdpCommunicationsServer.cs | 4 +- RSSDP/SsdpCommunicationsServer.cs | 168 +++++++------ RSSDP/SsdpConstants.cs | 2 + RSSDP/SsdpDeviceLocator.cs | 74 ++++-- RSSDP/SsdpDevicePublisher.cs | 64 +++-- .../Jellyfin.Networking.Tests/NetworkParseTests.cs | 9 +- 22 files changed, 363 insertions(+), 631 deletions(-) delete mode 100644 Emby.Server.Implementations/Net/UdpSocket.cs delete mode 100644 MediaBrowser.Common/Net/IPData.cs create mode 100644 MediaBrowser.Model/Net/IPData.cs delete mode 100644 MediaBrowser.Model/Net/ISocket.cs (limited to 'MediaBrowser.Common/Net/INetworkManager.cs') diff --git a/Emby.Dlna/Configuration/DlnaOptions.cs b/Emby.Dlna/Configuration/DlnaOptions.cs index e95a878c6..f233468de 100644 --- a/Emby.Dlna/Configuration/DlnaOptions.cs +++ b/Emby.Dlna/Configuration/DlnaOptions.cs @@ -17,7 +17,7 @@ namespace Emby.Dlna.Configuration BlastAliveMessages = true; SendOnlyMatchedHost = true; ClientDiscoveryIntervalSeconds = 60; - AliveMessageIntervalSeconds = 1800; + AliveMessageIntervalSeconds = 180; } /// diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 87c52163d..f6ec9574b 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -7,7 +7,6 @@ using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Sockets; -using System.Runtime.InteropServices; using System.Threading.Tasks; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; @@ -201,8 +200,7 @@ namespace Emby.Dlna.Main { if (_communicationsServer is null) { - var enableMultiSocketBinding = OperatingSystem.IsWindows() || - OperatingSystem.IsLinux(); + var enableMultiSocketBinding = OperatingSystem.IsWindows() || OperatingSystem.IsLinux(); _communicationsServer = new SsdpCommunicationsServer(_socketFactory, _networkManager, _logger, enableMultiSocketBinding) { @@ -248,11 +246,6 @@ namespace Emby.Dlna.Main public void StartDevicePublisher(Configuration.DlnaOptions options) { - if (!options.BlastAliveMessages) - { - return; - } - if (_publisher is not null) { return; @@ -263,7 +256,8 @@ namespace Emby.Dlna.Main _publisher = new SsdpDevicePublisher( _communicationsServer, Environment.OSVersion.Platform.ToString(), - Environment.OSVersion.VersionString, + // Can not use VersionString here since that includes OS and version + Environment.OSVersion.Version.ToString(), _config.GetDlnaConfiguration().SendOnlyMatchedHost) { LogFunction = (msg) => _logger.LogDebug("{Msg}", msg), @@ -272,7 +266,10 @@ namespace Emby.Dlna.Main RegisterServerEndpoints(); - _publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds)); + if (options.BlastAliveMessages) + { + _publisher.StartSendingAliveNotifications(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds)); + } } catch (Exception ex) { @@ -286,38 +283,32 @@ namespace Emby.Dlna.Main var descriptorUri = "/dlna/" + udn + "/description.xml"; // 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)) + // IPv6 is currently unsupported + var validInterfaces = _networkManager.GetInternalBindAddresses() + .Where(x => x.Address is not null) + .Where(x => x.AddressFamily != AddressFamily.InterNetworkV6) .ToList(); - if (bindAddresses.Count == 0) + if (validInterfaces.Count == 0) { - // No interfaces returned, so use loopback. - bindAddresses = _networkManager.GetLoopbacks().ToList(); + // No interfaces returned, fall back to loopback + validInterfaces = _networkManager.GetLoopbacks().ToList(); } - foreach (var address in bindAddresses) + foreach (var intf in validInterfaces) { - if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - // Not supporting IPv6 right now - continue; - } - var fullService = "urn:schemas-upnp-org:device:MediaServer:1"; - _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, address.Address); + _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, intf.Address); - var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(address.Address, false) + descriptorUri); + var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(intf.Address, false) + descriptorUri); var device = new SsdpRootDevice { CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info. Location = uri.Uri, // Must point to the URL that serves your devices UPnP description document. - Address = address.Address, - PrefixLength = NetworkExtensions.MaskToCidr(address.Subnet.Prefix), + Address = intf.Address, + PrefixLength = NetworkExtensions.MaskToCidr(intf.Subnet.Prefix), FriendlyName = "Jellyfin", Manufacturer = "Jellyfin", ModelName = "Jellyfin Server", diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs index 8a4e5ff45..43d673c77 100644 --- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs +++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs @@ -73,7 +73,11 @@ namespace Emby.Dlna.Ssdp { if (_listenerCount > 0 && _deviceLocator is null && _commsServer is not null) { - _deviceLocator = new SsdpDeviceLocator(_commsServer); + _deviceLocator = new SsdpDeviceLocator( + _commsServer, + Environment.OSVersion.Platform.ToString(), + // Can not use VersionString here since that includes OS and version + Environment.OSVersion.Version.ToString()); // (Optional) Set the filter so we only see notifications for devices we care about // (can be any search target value i.e device type, uuid value etc - any value that appears in the diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 50befaa53..485253bf7 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1025,7 +1025,7 @@ namespace Emby.Server.Implementations return PublishedServerUrl.Trim('/'); } - string smart = NetManager.GetBindInterface(hostname, out var port); + string smart = NetManager.GetBindAddress(hostname, out var port); return GetLocalApiUrl(smart.Trim('/'), null, port); } @@ -1033,7 +1033,7 @@ namespace Emby.Server.Implementations public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true) { // With an empty source, the port will be null - var smart = NetManager.GetBindAddress(ipAddress, out _); + var smart = NetManager.GetBindAddress(ipAddress, out _, true); var scheme = !allowHttps ? Uri.UriSchemeHttp : null; int? port = !allowHttps ? HttpPort : null; return GetLocalApiUrl(smart, scheme, port); diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs index b5a33a735..8fb1f9322 100644 --- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs +++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; @@ -80,31 +82,26 @@ namespace Emby.Server.Implementations.EntryPoints if (_enableMultiSocketBinding) { // Add global broadcast socket - _udpServers.Add(new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Broadcast, PortNumber)); + _udpServers.Add(new UdpServer(_logger, _appHost, _config, IPAddress.Broadcast, PortNumber)); // Add bind address specific broadcast sockets - foreach (var bindAddress in _networkManager.GetInternalBindAddresses()) + // IPv6 is currently unsupported + var validInterfaces = _networkManager.GetInternalBindAddresses().Where(i => i.AddressFamily == AddressFamily.InterNetwork); + foreach (var intf in validInterfaces) { - if (bindAddress.AddressFamily == AddressFamily.InterNetworkV6) - { - // Not supporting IPv6 right now - continue; - } - - var broadcastAddress = NetworkExtensions.GetBroadcastAddress(bindAddress.Subnet); + var broadcastAddress = NetworkExtensions.GetBroadcastAddress(intf.Subnet); _logger.LogDebug("Binding UDP server to {Address} on port {PortNumber}", broadcastAddress.ToString(), PortNumber); - _udpServers.Add(new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber)); + var server = new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber); + server.Start(_cancellationTokenSource.Token); + _udpServers.Add(server); } } else { - _udpServers.Add(new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Any, PortNumber)); - } - - foreach (var server in _udpServers) - { + var server = new UdpServer(_logger, _appHost, _config, IPAddress.Any, PortNumber); server.Start(_cancellationTokenSource.Token); + _udpServers.Add(server); } } catch (SocketException ex) @@ -133,9 +130,12 @@ namespace Emby.Server.Implementations.EntryPoints _cancellationTokenSource.Cancel(); _cancellationTokenSource.Dispose(); - _udpServers.ForEach(s => s.Dispose()); - _udpServers.Clear(); + foreach (var server in _udpServers) + { + server.Dispose(); + } + _udpServers.Clear(); _disposed = true; } } diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 98bbc1540..e76961ce9 100644 --- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -661,16 +661,16 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun // Need a way to set the Receive timeout on the socket otherwise this might never timeout? try { - await udpClient.SendToAsync(discBytes, 0, discBytes.Length, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 65001), cancellationToken).ConfigureAwait(false); + await udpClient.SendToAsync(discBytes, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 65001), cancellationToken).ConfigureAwait(false); var receiveBuffer = new byte[8192]; while (!cancellationToken.IsCancellationRequested) { - var response = await udpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false); - var deviceIp = response.RemoteEndPoint.Address.ToString(); + var response = await udpClient.ReceiveMessageFromAsync(receiveBuffer, new IPEndPoint(IPAddress.Any, 0), cancellationToken).ConfigureAwait(false); + 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 && response.Buffer[1] == 3) + // 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; diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs index b6d87a788..d134d948a 100644 --- a/Emby.Server.Implementations/Net/SocketFactory.cs +++ b/Emby.Server.Implementations/Net/SocketFactory.cs @@ -10,61 +10,63 @@ namespace Emby.Server.Implementations.Net public class SocketFactory : ISocketFactory { /// - public ISocket CreateUdpBroadcastSocket(int localPort) + public Socket CreateUdpBroadcastSocket(int localPort) { if (localPort < 0) { throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort)); } - var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { - retVal.EnableBroadcast = true; - retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); - retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); + socket.EnableBroadcast = true; + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); + socket.Bind(new IPEndPoint(IPAddress.Any, localPort)); - return new UdpSocket(retVal, localPort, IPAddress.Any); + return socket; } catch { - retVal?.Dispose(); + socket?.Dispose(); throw; } } /// - public ISocket CreateSsdpUdpSocket(IPAddress localIp, int localPort) + public Socket CreateSsdpUdpSocket(IPData bindInterface, int localPort) { + ArgumentNullException.ThrowIfNull(bindInterface.Address); + if (localPort < 0) { throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort)); } - var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { - retVal.EnableBroadcast = true; - retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); - retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4); + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + socket.Bind(new IPEndPoint(bindInterface.Address, localPort)); - retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), localIp)); - return new UdpSocket(retVal, localPort, localIp); + return socket; } catch { - retVal?.Dispose(); + socket?.Dispose(); throw; } } /// - public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress bindIpAddress, int multicastTimeToLive, int localPort) + public Socket CreateUdpMulticastSocket(IPAddress multicastAddress, IPData bindInterface, int multicastTimeToLive, int localPort) { - ArgumentNullException.ThrowIfNull(ipAddress); - ArgumentNullException.ThrowIfNull(bindIpAddress); + var bindIPAddress = bindInterface.Address; + ArgumentNullException.ThrowIfNull(multicastAddress); + ArgumentNullException.ThrowIfNull(bindIPAddress); if (multicastTimeToLive <= 0) { @@ -76,34 +78,25 @@ namespace Emby.Server.Implementations.Net throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort)); } - var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); - - retVal.ExclusiveAddressUse = false; - - try - { - // seeing occasional exceptions thrown on qnap - // System.Net.Sockets.SocketException (0x80004005): Protocol not available - retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); - } - catch (SocketException) - { - } + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { - retVal.EnableBroadcast = true; - // retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true); - retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive); + var interfaceIndex = (int)IPAddress.HostToNetworkOrder(bindInterface.Index); - retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ipAddress, bindIpAddress)); - retVal.MulticastLoopback = true; + socket.MulticastLoopback = false; + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, interfaceIndex); + socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, interfaceIndex)); + socket.Bind(new IPEndPoint(multicastAddress, localPort)); - return new UdpSocket(retVal, localPort, bindIpAddress); + return socket; } catch { - retVal?.Dispose(); + socket?.Dispose(); throw; } diff --git a/Emby.Server.Implementations/Net/UdpSocket.cs b/Emby.Server.Implementations/Net/UdpSocket.cs deleted file mode 100644 index 577b79283..000000000 --- a/Emby.Server.Implementations/Net/UdpSocket.cs +++ /dev/null @@ -1,267 +0,0 @@ -#nullable disable - -#pragma warning disable CS1591 - -using System; -using System.Net; -using System.Net.Sockets; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Model.Net; - -namespace Emby.Server.Implementations.Net -{ - // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS - // Be careful to check any changes compile and work for all platform projects it is shared in. - - public sealed class UdpSocket : ISocket, IDisposable - { - private readonly int _localPort; - - private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs() - { - SocketFlags = SocketFlags.None - }; - - private readonly SocketAsyncEventArgs _sendSocketAsyncEventArgs = new SocketAsyncEventArgs() - { - SocketFlags = SocketFlags.None - }; - - private Socket _socket; - private bool _disposed = false; - private TaskCompletionSource _currentReceiveTaskCompletionSource; - private TaskCompletionSource _currentSendTaskCompletionSource; - - public UdpSocket(Socket socket, int localPort, IPAddress ip) - { - ArgumentNullException.ThrowIfNull(socket); - - _socket = socket; - _localPort = localPort; - LocalIPAddress = ip; - - _socket.Bind(new IPEndPoint(ip, _localPort)); - - InitReceiveSocketAsyncEventArgs(); - } - - public UdpSocket(Socket socket, IPEndPoint endPoint) - { - ArgumentNullException.ThrowIfNull(socket); - - _socket = socket; - _socket.Connect(endPoint); - - InitReceiveSocketAsyncEventArgs(); - } - - public Socket Socket => _socket; - - public IPAddress LocalIPAddress { get; } - - private void InitReceiveSocketAsyncEventArgs() - { - var receiveBuffer = new byte[8192]; - _receiveSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length); - _receiveSocketAsyncEventArgs.Completed += OnReceiveSocketAsyncEventArgsCompleted; - - var sendBuffer = new byte[8192]; - _sendSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length); - _sendSocketAsyncEventArgs.Completed += OnSendSocketAsyncEventArgsCompleted; - } - - private void OnReceiveSocketAsyncEventArgsCompleted(object sender, SocketAsyncEventArgs e) - { - var tcs = _currentReceiveTaskCompletionSource; - if (tcs is not null) - { - _currentReceiveTaskCompletionSource = null; - - if (e.SocketError == SocketError.Success) - { - tcs.TrySetResult(new SocketReceiveResult - { - Buffer = e.Buffer, - ReceivedBytes = e.BytesTransferred, - RemoteEndPoint = e.RemoteEndPoint as IPEndPoint, - LocalIPAddress = LocalIPAddress - }); - } - else - { - tcs.TrySetException(new SocketException((int)e.SocketError)); - } - } - } - - private void OnSendSocketAsyncEventArgsCompleted(object sender, SocketAsyncEventArgs e) - { - var tcs = _currentSendTaskCompletionSource; - if (tcs is not null) - { - _currentSendTaskCompletionSource = null; - - if (e.SocketError == SocketError.Success) - { - tcs.TrySetResult(e.BytesTransferred); - } - else - { - tcs.TrySetException(new SocketException((int)e.SocketError)); - } - } - } - - public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback) - { - ThrowIfDisposed(); - - EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0); - - return _socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer); - } - - public int Receive(byte[] buffer, int offset, int count) - { - ThrowIfDisposed(); - - return _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); - } - - public SocketReceiveResult EndReceive(IAsyncResult result) - { - ThrowIfDisposed(); - - var sender = new IPEndPoint(IPAddress.Any, 0); - var remoteEndPoint = (EndPoint)sender; - - var receivedBytes = _socket.EndReceiveFrom(result, ref remoteEndPoint); - - var buffer = (byte[])result.AsyncState; - - return new SocketReceiveResult - { - ReceivedBytes = receivedBytes, - RemoteEndPoint = (IPEndPoint)remoteEndPoint, - Buffer = buffer, - LocalIPAddress = LocalIPAddress - }; - } - - public Task ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - var taskCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - bool isResultSet = false; - - Action callback = callbackResult => - { - try - { - if (!isResultSet) - { - isResultSet = true; - taskCompletion.TrySetResult(EndReceive(callbackResult)); - } - } - catch (Exception ex) - { - taskCompletion.TrySetException(ex); - } - }; - - var result = BeginReceive(buffer, offset, count, new AsyncCallback(callback)); - - if (result.CompletedSynchronously) - { - callback(result); - return taskCompletion.Task; - } - - cancellationToken.Register(() => taskCompletion.TrySetCanceled()); - - return taskCompletion.Task; - } - - public Task SendToAsync(byte[] buffer, int offset, int bytes, IPEndPoint endPoint, CancellationToken cancellationToken) - { - ThrowIfDisposed(); - - var taskCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - bool isResultSet = false; - - Action callback = callbackResult => - { - try - { - if (!isResultSet) - { - isResultSet = true; - taskCompletion.TrySetResult(EndSendTo(callbackResult)); - } - } - catch (Exception ex) - { - taskCompletion.TrySetException(ex); - } - }; - - var result = BeginSendTo(buffer, offset, bytes, endPoint, new AsyncCallback(callback), null); - - if (result.CompletedSynchronously) - { - callback(result); - return taskCompletion.Task; - } - - cancellationToken.Register(() => taskCompletion.TrySetCanceled()); - - return taskCompletion.Task; - } - - public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IPEndPoint endPoint, AsyncCallback callback, object state) - { - ThrowIfDisposed(); - - return _socket.BeginSendTo(buffer, offset, size, SocketFlags.None, endPoint, callback, state); - } - - public int EndSendTo(IAsyncResult result) - { - ThrowIfDisposed(); - - return _socket.EndSendTo(result); - } - - private void ThrowIfDisposed() - { - if (_disposed) - { - throw new ObjectDisposedException(nameof(UdpSocket)); - } - } - - /// - public void Dispose() - { - if (_disposed) - { - return; - } - - _socket?.Dispose(); - _receiveSocketAsyncEventArgs.Dispose(); - _sendSocketAsyncEventArgs.Dispose(); - _currentReceiveTaskCompletionSource?.TrySetCanceled(); - _currentSendTaskCompletionSource?.TrySetCanceled(); - - _socket = null; - _currentReceiveTaskCompletionSource = null; - _currentSendTaskCompletionSource = null; - - _disposed = true; - } - } -} diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 5f82950fc..cdd34bc89 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -9,6 +9,7 @@ using System.Threading; using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; +using MediaBrowser.Model.Net; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Logging; @@ -699,7 +700,7 @@ namespace Jellyfin.Networking.Manager } /// - public string GetBindInterface(string source, out int? port) + public string GetBindAddress(string source, out int? port) { if (!NetworkExtensions.TryParseHost(source, out var addresses, IsIPv4Enabled, IsIPv6Enabled)) { @@ -711,16 +712,16 @@ namespace Jellyfin.Networking.Manager } /// - public string GetBindInterface(HttpRequest source, out int? port) + public string GetBindAddress(HttpRequest source, out int? port) { - var result = GetBindInterface(source.Host.Host, out port); + var result = GetBindAddress(source.Host.Host, out port); port ??= source.Host.Port; return result; } /// - public string GetBindAddress(IPAddress? source, out int? port) + public string GetBindAddress(IPAddress? source, out int? port, bool skipOverrides = false) { port = null; @@ -741,7 +742,7 @@ namespace Jellyfin.Networking.Manager bool isExternal = !_lanSubnets.Any(network => network.Contains(source)); _logger.LogDebug("Trying to get bind address for source {Source} - External: {IsExternal}", source, isExternal); - if (MatchesPublishedServerUrl(source, isExternal, out result)) + if (!skipOverrides && MatchesPublishedServerUrl(source, isExternal, out result)) { return result; } diff --git a/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs b/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs index eac13f761..3cb791b57 100644 --- a/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs +++ b/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs @@ -41,7 +41,7 @@ public static class WebHostBuilderExtensions bool flagged = false; foreach (var netAdd in addresses) { - logger.LogInformation("Kestrel listening on {Address}", IPAddress.IPv6Any.Equals(netAdd.Address) ? "All Addresses" : netAdd); + logger.LogInformation("Kestrel is listening on {Address}", IPAddress.IPv6Any.Equals(netAdd.Address) ? "All IPv6 addresses" : netAdd.Address); options.Listen(netAdd.Address, appHost.HttpPort); if (appHost.ListenWithHttps) { diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 5721b19ca..68974f738 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; +using MediaBrowser.Model.Net; using Microsoft.AspNetCore.Http; namespace MediaBrowser.Common.Net @@ -70,27 +71,28 @@ namespace MediaBrowser.Common.Net /// Source of the request. /// Optional port returned, if it's part of an override. /// IP address to use, or loopback address if all else fails. - string GetBindInterface(HttpRequest source, out int? port); + string GetBindAddress(HttpRequest source, out int? port); /// /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . + /// (See . /// /// IP address of the request. /// Optional port returned, if it's part of an override. + /// Optional boolean denoting if published server overrides should be ignored. Defaults to false. /// IP address to use, or loopback address if all else fails. - string GetBindAddress(IPAddress source, out int? port); + string GetBindAddress(IPAddress source, out int? port, bool skipOverrides = false); /// /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . + /// (See . /// /// Source of the request. /// Optional port returned, if it's part of an override. /// IP address to use, or loopback address if all else fails. - string GetBindInterface(string source, out int? port); + string GetBindAddress(string source, out int? port); /// /// Get a list of all the MAC addresses associated with active interfaces. diff --git a/MediaBrowser.Common/Net/IPData.cs b/MediaBrowser.Common/Net/IPData.cs deleted file mode 100644 index 05842632c..000000000 --- a/MediaBrowser.Common/Net/IPData.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System.Net; -using System.Net.Sockets; -using Microsoft.AspNetCore.HttpOverrides; - -namespace MediaBrowser.Common.Net -{ - /// - /// Base network object class. - /// - public class IPData - { - /// - /// Initializes a new instance of the class. - /// - /// The . - /// The . - /// The interface 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 = name; - } - - /// - /// Initializes a new instance of the class. - /// - /// The . - /// The . - public IPData(IPAddress address, IPNetwork? subnet) - : this(address, subnet, string.Empty) - { - } - - /// - /// Gets or sets the object's IP address. - /// - public IPAddress Address { get; set; } - - /// - /// Gets or sets the object's IP address. - /// - public IPNetwork Subnet { get; set; } - - /// - /// Gets or sets the interface index. - /// - public int Index { get; set; } - - /// - /// Gets or sets the interface name. - /// - public string Name { get; set; } - - /// - /// Gets the AddressFamily of the object. - /// - public AddressFamily AddressFamily - { - get - { - if (Address.Equals(IPAddress.None)) - { - return Subnet.Prefix.AddressFamily.Equals(IPAddress.None) - ? AddressFamily.Unspecified - : Subnet.Prefix.AddressFamily; - } - else - { - return Address.AddressFamily; - } - } - } - } -} diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index 9a5804485..087e6369e 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -58,6 +58,7 @@ + diff --git a/MediaBrowser.Model/Net/IPData.cs b/MediaBrowser.Model/Net/IPData.cs new file mode 100644 index 000000000..16d74dcdd --- /dev/null +++ b/MediaBrowser.Model/Net/IPData.cs @@ -0,0 +1,75 @@ +using System.Net; +using System.Net.Sockets; +using Microsoft.AspNetCore.HttpOverrides; + +namespace MediaBrowser.Model.Net +{ + /// + /// Base network object class. + /// + public class IPData + { + /// + /// Initializes a new instance of the class. + /// + /// The . + /// The . + /// The interface 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 = name; + } + + /// + /// Initializes a new instance of the class. + /// + /// The . + /// The . + public IPData(IPAddress address, IPNetwork? subnet) + : this(address, subnet, string.Empty) + { + } + + /// + /// Gets or sets the object's IP address. + /// + public IPAddress Address { get; set; } + + /// + /// Gets or sets the object's IP address. + /// + public IPNetwork Subnet { get; set; } + + /// + /// Gets or sets the interface index. + /// + public int Index { get; set; } + + /// + /// Gets or sets the interface name. + /// + public string Name { get; set; } + + /// + /// Gets the AddressFamily of the object. + /// + public AddressFamily AddressFamily + { + get + { + if (Address.Equals(IPAddress.None)) + { + return Subnet.Prefix.AddressFamily.Equals(IPAddress.None) + ? AddressFamily.Unspecified + : Subnet.Prefix.AddressFamily; + } + else + { + return Address.AddressFamily; + } + } + } + } +} diff --git a/MediaBrowser.Model/Net/ISocket.cs b/MediaBrowser.Model/Net/ISocket.cs deleted file mode 100644 index 3de41d565..000000000 --- a/MediaBrowser.Model/Net/ISocket.cs +++ /dev/null @@ -1,34 +0,0 @@ -#pragma warning disable CS1591 - -using System; -using System.Net; -using System.Threading; -using System.Threading.Tasks; - -namespace MediaBrowser.Model.Net -{ - /// - /// Provides a common interface across platforms for UDP sockets used by this SSDP implementation. - /// - public interface ISocket : IDisposable - { - IPAddress LocalIPAddress { get; } - - Task ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken); - - IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback); - - SocketReceiveResult EndReceive(IAsyncResult result); - - /// - /// Sends a UDP message to a particular end point (uni or multicast). - /// - /// An array of type that contains the data to send. - /// The zero-based position in buffer at which to begin sending data. - /// The number of bytes to send. - /// An that represents the remote device. - /// The cancellation token to cancel operation. - /// The task object representing the asynchronous operation. - Task SendToAsync(byte[] buffer, int offset, int bytes, IPEndPoint endPoint, CancellationToken cancellationToken); - } -} diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs index f3bc31796..49a88c227 100644 --- a/MediaBrowser.Model/Net/ISocketFactory.cs +++ b/MediaBrowser.Model/Net/ISocketFactory.cs @@ -1,32 +1,36 @@ -#pragma warning disable CS1591 - using System.Net; +using System.Net.Sockets; namespace MediaBrowser.Model.Net { /// - /// Implemented by components that can create a platform specific UDP socket implementation, and wrap it in the cross platform interface. + /// Implemented by components that can create specific socket configurations. /// public interface ISocketFactory { - ISocket CreateUdpBroadcastSocket(int localPort); + /// + /// Creates a new unicast socket using the specified local port number. + /// + /// The local port to bind to. + /// A new unicast socket using the specified local port number. + Socket CreateUdpBroadcastSocket(int localPort); /// /// Creates a new unicast socket using the specified local port number. /// - /// The local IP address to bind to. + /// The bind interface. /// The local port to bind to. /// A new unicast socket using the specified local port number. - ISocket CreateSsdpUdpSocket(IPAddress localIp, int localPort); + Socket CreateSsdpUdpSocket(IPData bindInterface, int localPort); /// /// Creates a new multicast socket using the specified multicast IP address, multicast time to live and local port. /// - /// The multicast IP address to bind to. - /// The bind IP address. + /// The multicast IP address to bind to. + /// The bind interface. /// The multicast time to live value. Actually a maximum number of network hops for UDP packets. /// The local port to bind to. - /// A implementation. - ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress bindIpAddress, int multicastTimeToLive, int localPort); + /// A new multicast socket using the specfied bind interface, multicast address, multicast time to live and port. + Socket CreateUdpMulticastSocket(IPAddress multicastAddress, IPData bindInterface, int multicastTimeToLive, int localPort); } } diff --git a/RSSDP/ISsdpCommunicationsServer.cs b/RSSDP/ISsdpCommunicationsServer.cs index 3cbc991d6..571c66c10 100644 --- a/RSSDP/ISsdpCommunicationsServer.cs +++ b/RSSDP/ISsdpCommunicationsServer.cs @@ -23,12 +23,12 @@ namespace Rssdp.Infrastructure /// /// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications. /// - void BeginListeningForBroadcasts(); + void BeginListeningForMulticast(); /// /// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications. /// - void StopListeningForBroadcasts(); + void StopListeningForMulticast(); /// /// Sends a message to a particular address (uni or multicast) and port. diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs index fb5a66aa1..6ae260d55 100644 --- a/RSSDP/SsdpCommunicationsServer.cs +++ b/RSSDP/SsdpCommunicationsServer.cs @@ -25,18 +25,18 @@ namespace Rssdp.Infrastructure * Since stopping the service would be a bad idea (might not be allowed security wise and might * break other apps running on the system) the only other work around is to use two sockets. * - * We use one socket to listen for/receive notifications and search requests (_BroadcastListenSocket). - * We use a second socket, bound to a different local port, to send search requests and listen for - * responses (_SendSocket). The responses are sent to the local port this socket is bound to, - * which isn't port 1900 so the MS service doesn't steal them. While the caller can specify a local + * We use one group of sockets to listen for/receive notifications and search requests (_MulticastListenSockets). + * We use a second group, bound to a different local port, to send search requests and listen for + * responses (_SendSockets). The responses are sent to the local ports these sockets are bound to, + * which aren't port 1900 so the MS service doesn't steal them. While the caller can specify a local * port to use, we will default to 0 which allows the underlying system to auto-assign a free port. */ private object _BroadcastListenSocketSynchroniser = new object(); - private List _BroadcastListenSockets; + private List _MulticastListenSockets; private object _SendSocketSynchroniser = new object(); - private List _sendSockets; + private List _sendSockets; private HttpRequestParser _RequestParser; private HttpResponseParser _ResponseParser; @@ -78,7 +78,7 @@ namespace Rssdp.Infrastructure /// The argument is less than or equal to zero. public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive, INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding) { - if (socketFactory == null) + if (socketFactory is null) { throw new ArgumentNullException(nameof(socketFactory)); } @@ -107,25 +107,25 @@ namespace Rssdp.Infrastructure /// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications. /// /// Thrown if the property is true (because has been called previously). - public void BeginListeningForBroadcasts() + public void BeginListeningForMulticast() { ThrowIfDisposed(); lock (_BroadcastListenSocketSynchroniser) { - if (_BroadcastListenSockets == null) + if (_MulticastListenSockets is null) { try { - _BroadcastListenSockets = ListenForBroadcasts(); + _MulticastListenSockets = CreateMulticastSocketsAndListen(); } catch (SocketException ex) { - _logger.LogError("Failed to bind to port 1900: {Message}. DLNA will be unavailable", ex.Message); + _logger.LogError("Failed to bind to multicast address: {Message}. DLNA will be unavailable", ex.Message); } catch (Exception ex) { - _logger.LogError(ex, "Error in BeginListeningForBroadcasts"); + _logger.LogError(ex, "Error in BeginListeningForMulticast"); } } } @@ -135,15 +135,19 @@ namespace Rssdp.Infrastructure /// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications. /// /// Thrown if the property is true (because has been called previously). - public void StopListeningForBroadcasts() + public void StopListeningForMulticast() { lock (_BroadcastListenSocketSynchroniser) { - if (_BroadcastListenSockets != null) + if (_MulticastListenSockets is not null) { _logger.LogInformation("{0} disposing _BroadcastListenSocket", GetType().Name); - _BroadcastListenSockets.ForEach(s => s.Dispose()); - _BroadcastListenSockets = null; + foreach (var socket in _MulticastListenSockets) + { + socket.Dispose(); + } + + _MulticastListenSockets = null; } } } @@ -153,7 +157,7 @@ namespace Rssdp.Infrastructure /// public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) { - if (messageData == null) + if (messageData is null) { throw new ArgumentNullException(nameof(messageData)); } @@ -177,11 +181,11 @@ namespace Rssdp.Infrastructure } } - private async Task SendFromSocket(ISocket socket, byte[] messageData, IPEndPoint destination, CancellationToken cancellationToken) + private async Task SendFromSocket(Socket socket, byte[] messageData, IPEndPoint destination, CancellationToken cancellationToken) { try { - await socket.SendToAsync(messageData, 0, messageData.Length, destination, cancellationToken).ConfigureAwait(false); + await socket.SendToAsync(messageData, destination, cancellationToken).ConfigureAwait(false); } catch (ObjectDisposedException) { @@ -191,37 +195,42 @@ namespace Rssdp.Infrastructure } catch (Exception ex) { - _logger.LogError(ex, "Error sending socket message from {0} to {1}", socket.LocalIPAddress.ToString(), destination.ToString()); + var localIP = ((IPEndPoint)socket.LocalEndPoint).Address; + _logger.LogError(ex, "Error sending socket message from {0} to {1}", localIP.ToString(), destination.ToString()); } } - private List GetSendSockets(IPAddress fromLocalIpAddress, IPEndPoint destination) + private List GetSendSockets(IPAddress fromLocalIpAddress, IPEndPoint destination) { EnsureSendSocketCreated(); lock (_SendSocketSynchroniser) { - var sockets = _sendSockets.Where(i => i.LocalIPAddress.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) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.Any) || fromLocalIpAddress.Equals(i.LocalIPAddress)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromLocalIpAddress)); // If sending to the loopback address, filter the socket list as well if (destination.Address.Equals(IPAddress.Loopback)) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.Any) || i.LocalIPAddress.Equals(IPAddress.Loopback)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Loopback)); } } else if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetworkV6) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.IPv6Any) || fromLocalIpAddress.Equals(i.LocalIPAddress)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromLocalIpAddress)); // If sending to the loopback address, filter the socket list as well if (destination.Address.Equals(IPAddress.IPv6Loopback)) { - sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.IPv6Any) || i.LocalIPAddress.Equals(IPAddress.IPv6Loopback)); + sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any) + || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Loopback)); } } @@ -239,7 +248,7 @@ namespace Rssdp.Infrastructure /// public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) { - if (message == null) + if (message is null) { throw new ArgumentNullException(nameof(message)); } @@ -275,7 +284,7 @@ namespace Rssdp.Infrastructure { lock (_SendSocketSynchroniser) { - if (_sendSockets != null) + if (_sendSockets is not null) { var sockets = _sendSockets.ToList(); _sendSockets = null; @@ -284,7 +293,8 @@ namespace Rssdp.Infrastructure foreach (var socket in sockets) { - _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socket.LocalIPAddress); + var socketAddress = ((IPEndPoint)socket.LocalEndPoint).Address; + _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socketAddress); socket.Dispose(); } } @@ -312,7 +322,7 @@ namespace Rssdp.Infrastructure { if (disposing) { - StopListeningForBroadcasts(); + StopListeningForMulticast(); StopListeningForResponses(); } @@ -321,11 +331,11 @@ namespace Rssdp.Infrastructure private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken) { var sockets = _sendSockets; - if (sockets != null) + if (sockets is not null) { sockets = sockets.ToList(); - var tasks = sockets.Where(s => (fromLocalIpAddress == null || fromLocalIpAddress.Equals(s.LocalIPAddress))) + 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); } @@ -333,82 +343,78 @@ namespace Rssdp.Infrastructure return Task.CompletedTask; } - private List ListenForBroadcasts() + private List CreateMulticastSocketsAndListen() { - var sockets = new List(); - var nonNullBindAddresses = _networkManager.GetInternalBindAddresses().Where(x => x.Address != null); - + var sockets = new List(); + var multicastGroupAddress = IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress); if (_enableMultiSocketBinding) { - foreach (var address in nonNullBindAddresses) - { - if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - // Not supporting IPv6 right now - continue; - } + // IPv6 is currently unsupported + var validInterfaces = _networkManager.GetInternalBindAddresses() + .Where(x => x.Address is not null) + .Where(x => x.AddressFamily == AddressFamily.InterNetwork) + .DistinctBy(x => x.Index); + foreach (var intf in validInterfaces) + { try { - sockets.Add(_SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), address.Address, _MulticastTtl, SsdpConstants.MulticastPort)); + var socket = _SocketFactory.CreateUdpMulticastSocket(multicastGroupAddress, intf, _MulticastTtl, SsdpConstants.MulticastPort); + _ = ListenToSocketInternal(socket); + sockets.Add(socket); } catch (Exception ex) { - _logger.LogError(ex, "Error in ListenForBroadcasts. IPAddress: {0}", address); + _logger.LogError(ex, "Error in CreateMulticastSocketsAndListen. IP address: {0}", intf.Address); } } } else { - sockets.Add(_SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), IPAddress.Any, _MulticastTtl, SsdpConstants.MulticastPort)); - } - - foreach (var socket in sockets) - { + var socket = _SocketFactory.CreateUdpMulticastSocket(multicastGroupAddress, new IPData(IPAddress.Any, null), _MulticastTtl, SsdpConstants.MulticastPort); _ = ListenToSocketInternal(socket); + sockets.Add(socket); } return sockets; } - private List CreateSocketAndListenForResponsesAsync() + private List CreateSendSockets() { - var sockets = new List(); - + var sockets = new List(); if (_enableMultiSocketBinding) { - foreach (var address in _networkManager.GetInternalBindAddresses()) - { - if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - // Not supporting IPv6 right now - continue; - } + // IPv6 is currently unsupported + var validInterfaces = _networkManager.GetInternalBindAddresses() + .Where(x => x.Address is not null) + .Where(x => x.AddressFamily == AddressFamily.InterNetwork); + foreach (var intf in validInterfaces) + { try { - sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address.Address, _LocalPort)); + var socket = _SocketFactory.CreateSsdpUdpSocket(intf, _LocalPort); + _ = ListenToSocketInternal(socket); + sockets.Add(socket); } catch (Exception ex) { - _logger.LogError(ex, "Error in CreateSsdpUdpSocket. IPAddress: {0}", address); + _logger.LogError(ex, "Error in CreateSsdpUdpSocket. IPAddress: {0}", intf.Address); } } } else { - sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IPAddress.Any, _LocalPort)); - } - - foreach (var socket in sockets) - { + var socket = _SocketFactory.CreateSsdpUdpSocket(new IPData(IPAddress.Any, null), _LocalPort); _ = ListenToSocketInternal(socket); + sockets.Add(socket); } + return sockets; } - private async Task ListenToSocketInternal(ISocket socket) + private async Task ListenToSocketInternal(Socket socket) { var cancelled = false; var receiveBuffer = new byte[8192]; @@ -417,14 +423,17 @@ namespace Rssdp.Infrastructure { try { - var result = await socket.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, CancellationToken.None).ConfigureAwait(false); + var result = await socket.ReceiveMessageFromAsync(receiveBuffer, SocketFlags.None, new IPEndPoint(IPAddress.Any, 0), CancellationToken.None).ConfigureAwait(false);; if (result.ReceivedBytes > 0) { - // Strange cannot convert compiler error here if I don't explicitly - // assign or cast to Action first. Assignment is easier to read, - // so went with that. - ProcessMessage(UTF8Encoding.UTF8.GetString(result.Buffer, 0, result.ReceivedBytes), result.RemoteEndPoint, result.LocalIPAddress); + var remoteEndpoint = (IPEndPoint)result.RemoteEndPoint; + var localEndpointAddress = result.PacketInformation.Address; + + ProcessMessage( + UTF8Encoding.UTF8.GetString(receiveBuffer, 0, result.ReceivedBytes), + remoteEndpoint, + localEndpointAddress); } } catch (ObjectDisposedException) @@ -440,11 +449,11 @@ namespace Rssdp.Infrastructure private void EnsureSendSocketCreated() { - if (_sendSockets == null) + if (_sendSockets is null) { lock (_SendSocketSynchroniser) { - _sendSockets ??= CreateSocketAndListenForResponsesAsync(); + _sendSockets ??= CreateSendSockets(); } } } @@ -455,6 +464,7 @@ namespace Rssdp.Infrastructure // 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); if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase)) { HttpResponseMessage responseMessage = null; @@ -467,7 +477,7 @@ namespace Rssdp.Infrastructure // Ignore invalid packets. } - if (responseMessage != null) + if (responseMessage is not null) { OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress); } @@ -484,7 +494,7 @@ namespace Rssdp.Infrastructure // Ignore invalid packets. } - if (requestMessage != null) + if (requestMessage is not null) { OnRequestReceived(requestMessage, endPoint, receivedOnLocalIpAddress); } @@ -502,7 +512,7 @@ namespace Rssdp.Infrastructure } var handlers = this.RequestReceived; - if (handlers != null) + if (handlers is not null) { handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress)); } @@ -511,7 +521,7 @@ namespace Rssdp.Infrastructure private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIpAddress) { var handlers = this.ResponseReceived; - if (handlers != null) + if (handlers is not null) { handlers(this, new ResponseReceivedEventArgs(data, endPoint) { diff --git a/RSSDP/SsdpConstants.cs b/RSSDP/SsdpConstants.cs index 798f050e1..442f2b8f8 100644 --- a/RSSDP/SsdpConstants.cs +++ b/RSSDP/SsdpConstants.cs @@ -26,6 +26,8 @@ namespace Rssdp.Infrastructure internal const string SsdpDeviceDescriptionXmlNamespace = "urn:schemas-upnp-org:device-1-0"; + internal const string ServerVersion = "1.0"; + /// /// Default buffer size for receiving SSDP broadcasts. Value is 8192 (bytes). /// diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index 681ef0a5c..25c3b4c4e 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; - namespace Rssdp.Infrastructure { /// @@ -19,19 +19,48 @@ namespace Rssdp.Infrastructure private Timer _BroadcastTimer; private object _timerLock = new object(); + private string _OSName; + + private string _OSVersion; + private readonly TimeSpan DefaultSearchWaitTime = TimeSpan.FromSeconds(4); private readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1); /// /// Default constructor. /// - public SsdpDeviceLocator(ISsdpCommunicationsServer communicationsServer) + public SsdpDeviceLocator( + ISsdpCommunicationsServer communicationsServer, + string osName, + string osVersion) { - if (communicationsServer == null) + if (communicationsServer is null) { throw new ArgumentNullException(nameof(communicationsServer)); } + if (osName is null) + { + throw new ArgumentNullException(nameof(osName)); + } + + if (osName.Length == 0) + { + throw new ArgumentException("osName cannot be an empty string.", nameof(osName)); + } + + if (osVersion is null) + { + throw new ArgumentNullException(nameof(osVersion)); + } + + if (osVersion.Length == 0) + { + throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName)); + } + + _OSName = osName; + _OSVersion = osVersion; _CommunicationsServer = communicationsServer; _CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived; @@ -72,7 +101,7 @@ namespace Rssdp.Infrastructure { lock (_timerLock) { - if (_BroadcastTimer == null) + if (_BroadcastTimer is null) { _BroadcastTimer = new Timer(OnBroadcastTimerCallback, null, dueTime, period); } @@ -87,7 +116,7 @@ namespace Rssdp.Infrastructure { lock (_timerLock) { - if (_BroadcastTimer != null) + if (_BroadcastTimer is not null) { _BroadcastTimer.Dispose(); _BroadcastTimer = null; @@ -148,7 +177,7 @@ namespace Rssdp.Infrastructure private Task SearchAsync(string searchTarget, TimeSpan searchWaitTime, CancellationToken cancellationToken) { - if (searchTarget == null) + if (searchTarget is null) { throw new ArgumentNullException(nameof(searchTarget)); } @@ -187,7 +216,7 @@ namespace Rssdp.Infrastructure { _CommunicationsServer.RequestReceived -= CommsServer_RequestReceived; _CommunicationsServer.RequestReceived += CommsServer_RequestReceived; - _CommunicationsServer.BeginListeningForBroadcasts(); + _CommunicationsServer.BeginListeningForMulticast(); } /// @@ -219,7 +248,7 @@ namespace Rssdp.Infrastructure } var handlers = this.DeviceAvailable; - if (handlers != null) + if (handlers is not null) { handlers(this, new DeviceAvailableEventArgs(device, isNewDevice) { @@ -242,7 +271,7 @@ namespace Rssdp.Infrastructure } var handlers = this.DeviceUnavailable; - if (handlers != null) + if (handlers is not null) { handlers(this, new DeviceUnavailableEventArgs(device, expired)); } @@ -281,7 +310,7 @@ namespace Rssdp.Infrastructure var commsServer = _CommunicationsServer; _CommunicationsServer = null; - if (commsServer != null) + if (commsServer is not null) { commsServer.ResponseReceived -= this.CommsServer_ResponseReceived; commsServer.RequestReceived -= this.CommsServer_RequestReceived; @@ -295,7 +324,7 @@ namespace Rssdp.Infrastructure lock (_Devices) { var existingDevice = FindExistingDeviceNotification(_Devices, device.NotificationType, device.Usn); - if (existingDevice == null) + if (existingDevice is null) { _Devices.Add(device); isNewDevice = true; @@ -329,12 +358,13 @@ namespace Rssdp.Infrastructure private Task BroadcastDiscoverMessage(string serviceType, TimeSpan mxValue, CancellationToken cancellationToken) { + const string header = "M-SEARCH * HTTP/1.1"; + var values = new Dictionary(StringComparer.OrdinalIgnoreCase); values["HOST"] = "239.255.255.250:1900"; values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2"; - // values["X-EMBY-SERVERID"] = _appHost.SystemId; - + values["USER-AGENT"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion); values["MAN"] = "\"ssdp:discover\""; // Search target @@ -343,8 +373,6 @@ namespace Rssdp.Infrastructure // Seconds to delay response values["MX"] = "3"; - var header = "M-SEARCH * HTTP/1.1"; - var message = BuildMessage(header, values); return _CommunicationsServer.SendMulticastMessage(message, null, cancellationToken); @@ -358,7 +386,7 @@ namespace Rssdp.Infrastructure } var location = GetFirstHeaderUriValue("Location", message); - if (location != null) + if (location is not null) { var device = new DiscoveredSsdpDevice() { @@ -395,7 +423,7 @@ namespace Rssdp.Infrastructure private void ProcessAliveNotification(HttpRequestMessage message, IPAddress IpAddress) { var location = GetFirstHeaderUriValue("Location", message); - if (location != null) + if (location is not null) { var device = new DiscoveredSsdpDevice() { @@ -445,7 +473,7 @@ namespace Rssdp.Infrastructure if (message.Headers.Contains(headerName)) { message.Headers.TryGetValues(headerName, out values); - if (values != null) + if (values is not null) { retVal = values.FirstOrDefault(); } @@ -461,7 +489,7 @@ namespace Rssdp.Infrastructure if (message.Headers.Contains(headerName)) { message.Headers.TryGetValues(headerName, out values); - if (values != null) + if (values is not null) { retVal = values.FirstOrDefault(); } @@ -477,7 +505,7 @@ namespace Rssdp.Infrastructure if (request.Headers.Contains(headerName)) { request.Headers.TryGetValues(headerName, out values); - if (values != null) + if (values is not null) { value = values.FirstOrDefault(); } @@ -495,7 +523,7 @@ namespace Rssdp.Infrastructure if (response.Headers.Contains(headerName)) { response.Headers.TryGetValues(headerName, out values); - if (values != null) + if (values is not null) { value = values.FirstOrDefault(); } @@ -508,7 +536,7 @@ namespace Rssdp.Infrastructure private TimeSpan CacheAgeFromHeader(System.Net.Http.Headers.CacheControlHeaderValue headerValue) { - if (headerValue == null) + if (headerValue is null) { return TimeSpan.Zero; } @@ -565,7 +593,7 @@ namespace Rssdp.Infrastructure } } - if (existingDevices != null && existingDevices.Count > 0) + if (existingDevices is not null && existingDevices.Count > 0) { foreach (var removedDevice in existingDevices) { diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index adaac5fa3..40d93b6c0 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -4,10 +4,9 @@ using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Net; +using System.Text; using System.Threading; using System.Threading.Tasks; -using MediaBrowser.Common.Net; -using Microsoft.AspNetCore.HttpOverrides; namespace Rssdp.Infrastructure { @@ -32,8 +31,6 @@ namespace Rssdp.Infrastructure private Random _Random; - private const string ServerVersion = "1.0"; - /// /// Default constructor. /// @@ -43,12 +40,12 @@ namespace Rssdp.Infrastructure string osVersion, bool sendOnlyMatchedHost) { - if (communicationsServer == null) + if (communicationsServer is null) { throw new ArgumentNullException(nameof(communicationsServer)); } - if (osName == null) + if (osName is null) { throw new ArgumentNullException(nameof(osName)); } @@ -58,7 +55,7 @@ namespace Rssdp.Infrastructure throw new ArgumentException("osName cannot be an empty string.", nameof(osName)); } - if (osVersion == null) + if (osVersion is null) { throw new ArgumentNullException(nameof(osVersion)); } @@ -80,10 +77,13 @@ namespace Rssdp.Infrastructure _OSVersion = osVersion; _sendOnlyMatchedHost = sendOnlyMatchedHost; - _CommsServer.BeginListeningForBroadcasts(); + _CommsServer.BeginListeningForMulticast(); + + // Send alive notification once on creation + SendAllAliveNotifications(null); } - public void StartBroadcastingAliveMessages(TimeSpan interval) + public void StartSendingAliveNotifications(TimeSpan interval) { _RebroadcastAliveNotificationsTimer = new Timer(SendAllAliveNotifications, null, TimeSpan.FromSeconds(5), interval); } @@ -99,10 +99,9 @@ namespace Rssdp.Infrastructure /// The instance to add. /// Thrown if the argument is null. /// Thrown if the contains property values that are not acceptable to the UPnP 1.0 specification. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capture task to local variable suppresses compiler warning, but task is not really needed.")] public void AddDevice(SsdpRootDevice device) { - if (device == null) + if (device is null) { throw new ArgumentNullException(nameof(device)); } @@ -138,7 +137,7 @@ namespace Rssdp.Infrastructure /// Thrown if the argument is null. public async Task RemoveDevice(SsdpRootDevice device) { - if (device == null) + if (device is null) { throw new ArgumentNullException(nameof(device)); } @@ -200,7 +199,7 @@ namespace Rssdp.Infrastructure DisposeRebroadcastTimer(); var commsServer = _CommsServer; - if (commsServer != null) + if (commsServer is not null) { commsServer.RequestReceived -= this.CommsServer_RequestReceived; } @@ -209,7 +208,7 @@ namespace Rssdp.Infrastructure Task.WaitAll(tasks); _CommsServer = null; - if (commsServer != null) + if (commsServer is not null) { if (!commsServer.IsShared) { @@ -282,23 +281,23 @@ namespace Rssdp.Infrastructure } else if (searchTarget.Trim().StartsWith("uuid:", StringComparison.OrdinalIgnoreCase)) { - devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray(); + devices = GetAllDevicesAsFlatEnumerable().Where(d => String.Compare(d.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0).ToArray(); } else if (searchTarget.StartsWith("urn:", StringComparison.OrdinalIgnoreCase)) { - devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray(); + devices = GetAllDevicesAsFlatEnumerable().Where(d => String.Compare(d.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0).ToArray(); } } - if (devices != null) + if (devices is not null) { - var deviceList = devices.ToList(); // WriteTrace(String.Format("Sending {0} search responses", deviceList.Count)); - foreach (var device in deviceList) + foreach (var device in devices) { var root = device.ToRootDevice(); - if (!_sendOnlyMatchedHost || root.Address.Equals(remoteEndPoint.Address)) + + if (!_sendOnlyMatchedHost || root.Address.Equals(receivedOnlocalIpAddress)) { SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken); } @@ -318,7 +317,7 @@ namespace Rssdp.Infrastructure IPAddress receivedOnlocalIpAddress, CancellationToken cancellationToken) { - bool isRootDevice = (device as SsdpRootDevice) != null; + bool isRootDevice = (device as SsdpRootDevice) is not null; if (isRootDevice) { SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken); @@ -346,19 +345,17 @@ namespace Rssdp.Infrastructure IPAddress receivedOnlocalIpAddress, CancellationToken cancellationToken) { - var rootDevice = device.ToRootDevice(); - - // var additionalheaders = FormatCustomHeadersForResponse(device); - const string header = "HTTP/1.1 200 OK"; + var rootDevice = device.ToRootDevice(); var values = new Dictionary(StringComparer.OrdinalIgnoreCase); values["EXT"] = ""; values["DATE"] = DateTime.UtcNow.ToString("r"); + values["HOST"] = "239.255.255.250:1900"; values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds; values["ST"] = searchTarget; - values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion); + values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion); values["USN"] = uniqueServiceName; values["LOCATION"] = rootDevice.Location.ToString(); @@ -367,7 +364,7 @@ namespace Rssdp.Infrastructure try { await _CommsServer.SendMessage( - System.Text.Encoding.UTF8.GetBytes(message), + Encoding.UTF8.GetBytes(message), endPoint, receivedOnlocalIpAddress, cancellationToken) @@ -492,7 +489,7 @@ namespace Rssdp.Infrastructure values["DATE"] = DateTime.UtcNow.ToString("r"); values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds; values["LOCATION"] = rootDevice.Location.ToString(); - values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion); + values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion); values["NTS"] = "ssdp:alive"; values["NT"] = notificationType; values["USN"] = uniqueServiceName; @@ -527,7 +524,6 @@ namespace Rssdp.Infrastructure return Task.WhenAll(tasks); } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "byebye", Justification = "Correct value for this type of notification in SSDP.")] private Task SendByeByeNotification(SsdpDevice device, string notificationType, string uniqueServiceName, CancellationToken cancellationToken) { const string header = "NOTIFY * HTTP/1.1"; @@ -537,7 +533,7 @@ namespace Rssdp.Infrastructure // If needed later for non-server devices, these headers will need to be dynamic values["HOST"] = "239.255.255.250:1900"; values["DATE"] = DateTime.UtcNow.ToString("r"); - values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion); + values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion); values["NTS"] = "ssdp:byebye"; values["NT"] = notificationType; values["USN"] = uniqueServiceName; @@ -553,7 +549,7 @@ namespace Rssdp.Infrastructure { var timer = _RebroadcastAliveNotificationsTimer; _RebroadcastAliveNotificationsTimer = null; - if (timer != null) + if (timer is not null) { timer.Dispose(); } @@ -581,7 +577,7 @@ namespace Rssdp.Infrastructure { string retVal = null; IEnumerable values = null; - if (httpRequestHeaders.TryGetValues(headerName, out values) && values != null) + if (httpRequestHeaders.TryGetValues(headerName, out values) && values is not null) { retVal = values.FirstOrDefault(); } @@ -593,7 +589,7 @@ namespace Rssdp.Infrastructure private void WriteTrace(string text) { - if (LogFunction != null) + if (LogFunction is not null) { LogFunction(text); } @@ -603,7 +599,7 @@ namespace Rssdp.Infrastructure private void WriteTrace(string text, SsdpDevice device) { var rootDevice = device as SsdpRootDevice; - if (rootDevice != null) + if (rootDevice is not null) { WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid + " - " + rootDevice.Location); } diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index c493ce5ea..10706e9c2 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -6,6 +6,7 @@ using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; +using MediaBrowser.Model.Net; using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; @@ -210,7 +211,7 @@ namespace Jellyfin.Networking.Tests if (resultObj is not null && host.Length > 0) { result = resultObj.First().Address.ToString(); - var intf = nm.GetBindInterface(source, out _); + var intf = nm.GetBindAddress(source, out _); Assert.Equal(intf, result); } @@ -271,7 +272,7 @@ namespace Jellyfin.Networking.Tests result = resultObj.First().Address.ToString(); } - var intf = nm.GetBindInterface(source, out int? _); + var intf = nm.GetBindAddress(source, out int? _); Assert.Equal(result, intf); } @@ -334,7 +335,7 @@ namespace Jellyfin.Networking.Tests NetworkManager.MockNetworkSettings = interfaces; using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - var interfaceToUse = nm.GetBindInterface(string.Empty, out _); + var interfaceToUse = nm.GetBindAddress(string.Empty, out _); Assert.Equal(result, interfaceToUse); } @@ -358,7 +359,7 @@ namespace Jellyfin.Networking.Tests NetworkManager.MockNetworkSettings = interfaces; using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - var interfaceToUse = nm.GetBindInterface(source, out _); + var interfaceToUse = nm.GetBindAddress(source, out _); Assert.Equal(result, interfaceToUse); } -- 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/INetworkManager.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 a5f16136eb171b17b1e1ed661e9aeb017522ce89 Mon Sep 17 00:00:00 2001 From: Shadowghost Date: Mon, 20 Feb 2023 16:58:22 +0100 Subject: Apply review suggestions --- MediaBrowser.Common/Net/INetworkManager.cs | 1 - MediaBrowser.Model/Net/IPData.cs | 109 ++++++++++++++--------------- MediaBrowser.Model/Net/ISocketFactory.cs | 53 +++++++------- RSSDP/SsdpDeviceLocator.cs | 28 +------- RSSDP/SsdpDevicePublisher.cs | 27 +------ 5 files changed, 86 insertions(+), 132 deletions(-) (limited to 'MediaBrowser.Common/Net/INetworkManager.cs') diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index efd87a810..1a3176b58 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -76,7 +76,6 @@ namespace MediaBrowser.Common.Net /// /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// If no bind addresses are specified, an internal interface address is selected. - /// (See . /// /// IP address of the request. /// Optional port returned, if it's part of an override. diff --git a/MediaBrowser.Model/Net/IPData.cs b/MediaBrowser.Model/Net/IPData.cs index 16d74dcdd..985b16c6e 100644 --- a/MediaBrowser.Model/Net/IPData.cs +++ b/MediaBrowser.Model/Net/IPData.cs @@ -2,73 +2,72 @@ using System.Net; using System.Net.Sockets; using Microsoft.AspNetCore.HttpOverrides; -namespace MediaBrowser.Model.Net +namespace MediaBrowser.Model.Net; + +/// +/// Base network object class. +/// +public class IPData { /// - /// Base network object class. + /// Initializes a new instance of the class. /// - public class IPData + /// The . + /// The . + /// The interface name. + public IPData(IPAddress address, IPNetwork? subnet, string name) { - /// - /// Initializes a new instance of the class. - /// - /// The . - /// The . - /// The interface 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 = name; - } + Address = address; + Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128)); + Name = name; + } - /// - /// Initializes a new instance of the class. - /// - /// The . - /// The . - public IPData(IPAddress address, IPNetwork? subnet) - : this(address, subnet, string.Empty) - { - } + /// + /// Initializes a new instance of the class. + /// + /// The . + /// The . + public IPData(IPAddress address, IPNetwork? subnet) + : this(address, subnet, string.Empty) + { + } - /// - /// Gets or sets the object's IP address. - /// - public IPAddress Address { get; set; } + /// + /// Gets or sets the object's IP address. + /// + public IPAddress Address { get; set; } - /// - /// Gets or sets the object's IP address. - /// - public IPNetwork Subnet { get; set; } + /// + /// Gets or sets the object's IP address. + /// + public IPNetwork Subnet { get; set; } - /// - /// Gets or sets the interface index. - /// - public int Index { get; set; } + /// + /// Gets or sets the interface index. + /// + public int Index { get; set; } - /// - /// Gets or sets the interface name. - /// - public string Name { get; set; } + /// + /// Gets or sets the interface name. + /// + public string Name { get; set; } - /// - /// Gets the AddressFamily of the object. - /// - public AddressFamily AddressFamily + /// + /// Gets the AddressFamily of the object. + /// + public AddressFamily AddressFamily + { + get { - get + if (Address.Equals(IPAddress.None)) + { + return Subnet.Prefix.AddressFamily.Equals(IPAddress.None) + ? AddressFamily.Unspecified + : Subnet.Prefix.AddressFamily; + } + else { - if (Address.Equals(IPAddress.None)) - { - return Subnet.Prefix.AddressFamily.Equals(IPAddress.None) - ? AddressFamily.Unspecified - : Subnet.Prefix.AddressFamily; - } - else - { - return Address.AddressFamily; - } + return Address.AddressFamily; } } } diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs index 49a88c227..128034eb8 100644 --- a/MediaBrowser.Model/Net/ISocketFactory.cs +++ b/MediaBrowser.Model/Net/ISocketFactory.cs @@ -1,36 +1,35 @@ using System.Net; using System.Net.Sockets; -namespace MediaBrowser.Model.Net +namespace MediaBrowser.Model.Net; + +/// +/// Implemented by components that can create specific socket configurations. +/// +public interface ISocketFactory { /// - /// Implemented by components that can create specific socket configurations. + /// Creates a new unicast socket using the specified local port number. /// - public interface ISocketFactory - { - /// - /// Creates a new unicast socket using the specified local port number. - /// - /// The local port to bind to. - /// A new unicast socket using the specified local port number. - Socket CreateUdpBroadcastSocket(int localPort); + /// The local port to bind to. + /// A new unicast socket using the specified local port number. + Socket CreateUdpBroadcastSocket(int localPort); - /// - /// Creates a new unicast socket using the specified local port number. - /// - /// The bind interface. - /// The local port to bind to. - /// A new unicast socket using the specified local port number. - Socket CreateSsdpUdpSocket(IPData bindInterface, int localPort); + /// + /// Creates a new unicast socket using the specified local port number. + /// + /// The bind interface. + /// The local port to bind to. + /// A new unicast socket using the specified local port number. + Socket CreateSsdpUdpSocket(IPData bindInterface, int localPort); - /// - /// Creates a new multicast socket using the specified multicast IP address, multicast time to live and local port. - /// - /// The multicast IP address to bind to. - /// The bind interface. - /// The multicast time to live value. Actually a maximum number of network hops for UDP packets. - /// The local port to bind to. - /// A new multicast socket using the specfied bind interface, multicast address, multicast time to live and port. - Socket CreateUdpMulticastSocket(IPAddress multicastAddress, IPData bindInterface, int multicastTimeToLive, int localPort); - } + /// + /// Creates a new multicast socket using the specified multicast IP address, multicast time to live and local port. + /// + /// The multicast IP address to bind to. + /// The bind interface. + /// The multicast time to live value. Actually a maximum number of network hops for UDP packets. + /// The local port to bind to. + /// A new multicast socket using the specfied bind interface, multicast address, multicast time to live and port. + Socket CreateUdpMulticastSocket(IPAddress multicastAddress, IPData bindInterface, int multicastTimeToLive, int localPort); } diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs index 9d756d0d4..ffe97754c 100644 --- a/RSSDP/SsdpDeviceLocator.cs +++ b/RSSDP/SsdpDeviceLocator.cs @@ -34,30 +34,9 @@ namespace Rssdp.Infrastructure string osName, string osVersion) { - if (communicationsServer is null) - { - throw new ArgumentNullException(nameof(communicationsServer)); - } - - if (osName is null) - { - throw new ArgumentNullException(nameof(osName)); - } - - if (osName.Length == 0) - { - throw new ArgumentException("osName cannot be an empty string.", nameof(osName)); - } - - if (osVersion is null) - { - throw new ArgumentNullException(nameof(osVersion)); - } - - if (osVersion.Length == 0) - { - throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName)); - } + ArgumentNullException.ThrowIfNull(communicationsServer); + ArgumentNullException.ThrowIfNullOrEmpty(osName); + ArgumentNullException.ThrowIfNullOrEmpty(osVersion); _OSName = osName; _OSVersion = osVersion; @@ -363,7 +342,6 @@ namespace Rssdp.Infrastructure var values = new Dictionary(StringComparer.OrdinalIgnoreCase); values["HOST"] = "239.255.255.250:1900"; - values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2"; values["USER-AGENT"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion); values["MAN"] = "\"ssdp:discover\""; diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index 8b5551899..e443c6285 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -40,30 +40,9 @@ namespace Rssdp.Infrastructure string osVersion, bool sendOnlyMatchedHost) { - if (communicationsServer is null) - { - throw new ArgumentNullException(nameof(communicationsServer)); - } - - if (osName is null) - { - throw new ArgumentNullException(nameof(osName)); - } - - if (osName.Length == 0) - { - throw new ArgumentException("osName cannot be an empty string.", nameof(osName)); - } - - if (osVersion is null) - { - throw new ArgumentNullException(nameof(osVersion)); - } - - if (osVersion.Length == 0) - { - throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName)); - } + ArgumentNullException.ThrowIfNull(communicationsServer); + ArgumentNullException.ThrowIfNullOrEmpty(osName); + ArgumentNullException.ThrowIfNullOrEmpty(osVersion); _SupportPnpRootDevice = true; _Devices = new List(); -- 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/INetworkManager.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 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/INetworkManager.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