diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs index 15021c19d6..01a9def0bf 100644 --- a/Emby.Dlna/Main/DlnaEntryPoint.cs +++ b/Emby.Dlna/Main/DlnaEntryPoint.cs @@ -3,15 +3,16 @@ #pragma warning disable CS1591 using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Threading.Tasks; using Emby.Dlna.PlayTo; using Emby.Dlna.Ssdp; using Jellyfin.Networking.Configuration; -using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; @@ -285,9 +286,11 @@ namespace Emby.Dlna.Main var udn = CreateUuid(_appHost.SystemId); var descriptorUri = "/dlna/" + udn + "/description.xml"; - var bindAddresses = NetworkManager.CreateCollection( - _networkManager.GetInternalBindAddresses() - .Where(i => i.AddressFamily == AddressFamily.InterNetwork || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0))); + var bindAddresses = _networkManager + .GetInternalBindAddresses() + .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork + || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0)) + .ToList(); if (bindAddresses.Count == 0) { @@ -295,7 +298,7 @@ namespace Emby.Dlna.Main bindAddresses = _networkManager.GetLoopbacks(); } - foreach (IPNetAddress address in bindAddresses) + foreach (var address in bindAddresses) { if (address.AddressFamily == AddressFamily.InterNetworkV6) { @@ -304,7 +307,7 @@ namespace Emby.Dlna.Main } // Limit to LAN addresses only - if (!_networkManager.IsInLocalNetwork(address)) + if (!_networkManager.IsInLocalNetwork(address.Address)) { continue; } @@ -313,14 +316,14 @@ namespace Emby.Dlna.Main _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, address); - var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(address, false) + descriptorUri); + var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(address.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 = address.PrefixLength, + PrefixLength = NetworkExtensions.MaskToCidr(address.Subnet.Prefix), FriendlyName = "Jellyfin", Manufacturer = "Jellyfin", ModelName = "Jellyfin Server", diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 32289625fe..a0ad4a9ab5 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -1114,10 +1114,10 @@ namespace Emby.Server.Implementations } /// - public string GetApiUrlForLocalAccess(IPObject hostname = null, bool allowHttps = true) + public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true) { // With an empty source, the port will be null - var smart = NetManager.GetBindInterface(hostname ?? IPHost.None, out _); + var smart = NetManager.GetBindInterface(ipAddress, out _); var scheme = !allowHttps ? Uri.UriSchemeHttp : null; int? port = !allowHttps ? HttpPort : null; return GetLocalApiUrl(smart, scheme, port); diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 61db223d92..0ac55c986e 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -113,12 +113,12 @@ namespace Jellyfin.Networking.Configuration public string UDPPortRange { get; set; } = string.Empty; /// - /// Gets or sets a value indicating whether gets or sets IPV6 capability. + /// Gets or sets a value indicating whether IPv6 is enabled or not. /// public bool EnableIPV6 { get; set; } /// - /// Gets or sets a value indicating whether gets or sets IPV4 capability. + /// Gets or sets a value indicating whether IPv6 is enabled or not. /// public bool EnableIPV4 { get; set; } = true; @@ -165,12 +165,6 @@ namespace Jellyfin.Networking.Configuration /// public bool EnableMultiSocketBinding { get; } = true; - /// - /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network. - /// Depending on the address range implemented ULA ranges might not be used. - /// - public bool TrustAllIP6Interfaces { get; set; } - /// /// Gets or sets the ports that HDHomerun uses. /// diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 4b7b87814c..f51fd85dd5 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net; @@ -12,30 +11,25 @@ using Jellyfin.Networking.Configuration; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Logging; namespace Jellyfin.Networking.Manager { /// /// Class to take care of network interface management. - /// Note: The normal collection methods and properties will not work with Collection{IPObject}. . /// public class NetworkManager : INetworkManager, IDisposable { - /// - /// Contains the description of the interface along with its index. - /// - private readonly Dictionary _interfaceNames; - /// /// Threading lock for network properties. /// - private readonly object _intLock = new object(); + private readonly object _initLock; /// - /// List of all interface addresses and masks. + /// Dictionary containing interface addresses and their subnets. /// - private readonly Collection _interfaceAddresses; + private readonly List _interfaces; /// /// List of all interface MAC addresses. @@ -49,9 +43,11 @@ namespace Jellyfin.Networking.Manager private readonly object _eventFireLock; /// - /// Holds the bind address overrides. + /// Holds the published server URLs and the IPs to use them on. /// - private readonly Dictionary _publishedServerUrls; + private readonly Dictionary _publishedServerUrls; + + private Collection _remoteAddressFilter; /// /// Used to stop "event-racing conditions". @@ -59,35 +55,25 @@ namespace Jellyfin.Networking.Manager private bool _eventfire; /// - /// Unfiltered user defined LAN subnets. () + /// Unfiltered user defined LAN subnets () /// or internal interface network subnets if undefined by user. /// - private Collection _lanSubnets; + private Collection _lanSubnets; /// /// User defined list of subnets to excluded from the LAN. /// - private Collection _excludedSubnets; + private Collection _excludedSubnets; /// - /// List of interface addresses to bind the WS. + /// List of interfaces to bind to. /// - private Collection _bindAddresses; + private List _bindAddresses; /// /// List of interface addresses to exclude from bind. /// - private Collection _bindExclusions; - - /// - /// Caches list of all internal filtered interface addresses and masks. - /// - private Collection _internalInterfaces; - - /// - /// Flag set when no custom LAN has been defined in the configuration. - /// - private bool _usingPrivateAddresses; + private List _bindExclusions; /// /// True if this object is disposed. @@ -104,12 +90,12 @@ namespace Jellyfin.Networking.Manager { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager)); - - _interfaceAddresses = new Collection(); + _initLock = new(); + _interfaces = new List(); _macAddresses = new List(); - _interfaceNames = new Dictionary(); - _publishedServerUrls = new Dictionary(); + _publishedServerUrls = new Dictionary(); _eventFireLock = new object(); + _remoteAddressFilter = new Collection(); UpdateSettings(_configurationManager.GetNetworkConfiguration()); @@ -131,46 +117,24 @@ namespace Jellyfin.Networking.Manager public static string MockNetworkSettings { get; set; } = string.Empty; /// - /// Gets or sets a value indicating whether IP6 is enabled. + /// Gets a value indicating whether IP4 is enabled. /// - public bool IsIP6Enabled { get; set; } + public bool IsIpv4Enabled => _configurationManager.GetNetworkConfiguration().EnableIPV4; /// - /// Gets or sets a value indicating whether IP4 is enabled. + /// Gets a value indicating whether IP6 is enabled. /// - public bool IsIP4Enabled { get; set; } - - /// - public Collection RemoteAddressFilter { get; private set; } + public bool IsIpv6Enabled => _configurationManager.GetNetworkConfiguration().EnableIPV6; /// /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. /// - public bool TrustAllIP6Interfaces { get; internal set; } + public bool TrustAllIpv6Interfaces { get; private set; } /// /// Gets the Published server override list. /// - public Dictionary PublishedServerUrls => _publishedServerUrls; - - /// - /// Creates a new network collection. - /// - /// Items to assign the collection, or null. - /// The collection created. - public static Collection CreateCollection(IEnumerable? source = null) - { - var result = new Collection(); - if (source != null) - { - foreach (var item in source) - { - result.AddItem(item, false); - } - } - - return result; - } + public Dictionary PublishedServerUrls => _publishedServerUrls; /// public void Dispose() @@ -179,643 +143,6 @@ namespace Jellyfin.Networking.Manager GC.SuppressFinalize(this); } - /// - public IReadOnlyCollection GetMacAddresses() - { - // Populated in construction - so always has values. - return _macAddresses; - } - - /// - public bool IsGatewayInterface(IPObject? addressObj) - { - var address = addressObj?.Address ?? IPAddress.None; - return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0); - } - - /// - public bool IsGatewayInterface(IPAddress? addressObj) - { - return _internalInterfaces.Any(i => i.Address.Equals(addressObj ?? IPAddress.None) && i.Tag < 0); - } - - /// - public Collection GetLoopbacks() - { - Collection nc = new Collection(); - if (IsIP4Enabled) - { - nc.AddItem(IPAddress.Loopback); - } - - if (IsIP6Enabled) - { - nc.AddItem(IPAddress.IPv6Loopback); - } - - return nc; - } - - /// - public bool IsExcluded(IPAddress ip) - { - return _excludedSubnets.ContainsAddress(ip); - } - - /// - public bool IsExcluded(EndPoint ip) - { - return ip != null && IsExcluded(((IPEndPoint)ip).Address); - } - - /// - public Collection CreateIPCollection(string[] values, bool negated = false) - { - Collection col = new Collection(); - if (values == null) - { - return col; - } - - for (int a = 0; a < values.Length; a++) - { - string v = values[a].Trim(); - - try - { - if (v.StartsWith('!')) - { - if (negated) - { - AddToCollection(col, v[1..]); - } - } - else if (!negated) - { - AddToCollection(col, v); - } - } - catch (ArgumentException e) - { - _logger.LogWarning(e, "Ignoring LAN value {Value}.", v); - } - } - - return col; - } - - /// - public Collection GetAllBindInterfaces(bool individualInterfaces = false) - { - int count = _bindAddresses.Count; - - if (count == 0) - { - if (_bindExclusions.Count > 0) - { - // Return all the interfaces except the ones specifically excluded. - return _interfaceAddresses.Exclude(_bindExclusions, false); - } - - if (individualInterfaces) - { - return new Collection(_interfaceAddresses); - } - - // No bind address and no exclusions, so listen on all interfaces. - Collection result = new Collection(); - - if (IsIP6Enabled && IsIP4Enabled) - { - // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any - result.AddItem(IPAddress.IPv6Any); - } - else if (IsIP4Enabled) - { - result.AddItem(IPAddress.Any); - } - else if (IsIP6Enabled) - { - // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses. - foreach (var iface in _interfaceAddresses) - { - if (iface.AddressFamily == AddressFamily.InterNetworkV6) - { - result.AddItem(iface.Address); - } - } - } - - return result; - } - - // Remove any excluded bind interfaces. - return _bindAddresses.Exclude(_bindExclusions, false); - } - - /// - public string GetBindInterface(string source, out int? port) - { - if (!string.IsNullOrEmpty(source) && IPHost.TryParse(source, out IPHost host)) - { - return GetBindInterface(host, out port); - } - - return GetBindInterface(IPHost.None, out port); - } - - /// - public string GetBindInterface(IPAddress source, out int? port) - { - return GetBindInterface(new IPNetAddress(source), out port); - } - - /// - public string GetBindInterface(HttpRequest source, out int? port) - { - string result; - - if (source != null && IPHost.TryParse(source.Host.Host, out IPHost host)) - { - result = GetBindInterface(host, out port); - port ??= source.Host.Port; - } - else - { - result = GetBindInterface(IPNetAddress.None, out port); - port ??= source?.Host.Port; - } - - return result; - } - - /// - public string GetBindInterface(IPObject source, out int? port) - { - port = null; - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - // Do we have a source? - bool haveSource = !source.Address.Equals(IPAddress.None); - bool isExternal = false; - - if (haveSource) - { - if (!IsIP6Enabled && 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 (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork) - { - _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); - } - - isExternal = !IsInLocalNetwork(source); - - if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) - { - _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port); - return res; - } - } - - _logger.LogDebug("GetBindInterface: Source: {HaveSource}, External: {IsExternal}:", haveSource, isExternal); - - // No preference given, so move on to bind addresses. - if (MatchesBindInterface(source, isExternal, out string result)) - { - return result; - } - - if (isExternal && MatchesExternalInterface(source, out result)) - { - return result; - } - - // Get the first LAN interface address that isn't a loopback. - var interfaces = CreateCollection( - _interfaceAddresses - .Exclude(_bindExclusions, false) - .Where(IsInLocalNetwork) - .OrderBy(p => p.Tag)); - - if (interfaces.Count > 0) - { - if (haveSource) - { - foreach (var intf in interfaces) - { - if (intf.Address.Equals(source.Address)) - { - result = FormatIP6String(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface. {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 interfaces) - { - if (intf.Contains(source)) - { - result = FormatIP6String(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result); - return result; - } - } - } - - result = FormatIP6String(interfaces.First().Address); - _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result); - return result; - } - - // There isn't any others, so we'll use the loopback. - result = IsIP6Enabled ? "::1" : "127.0.0.1"; - _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result); - return result; - } - - /// - public Collection GetInternalBindAddresses() - { - int count = _bindAddresses.Count; - - if (count == 0) - { - if (_bindExclusions.Count > 0) - { - // Return all the internal interfaces except the ones excluded. - return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p))); - } - - // No bind address, so return all internal interfaces. - return CreateCollection(_internalInterfaces); - } - - return new Collection(_bindAddresses.Where(a => IsInLocalNetwork(a)).ToArray()); - } - - /// - public bool IsInLocalNetwork(IPObject address) - { - return IsInLocalNetwork(address.Address); - } - - /// - public bool IsInLocalNetwork(string address) - { - return IPHost.TryParse(address, out IPHost ipHost) && IsInLocalNetwork(ipHost); - } - - /// - public bool IsInLocalNetwork(IPAddress address) - { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } - - if (address.Equals(IPAddress.None)) - { - return false; - } - - // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. - if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) - { - return true; - } - - // As private addresses can be redefined by Configuration.LocalNetworkAddresses - return IPAddress.IsLoopback(address) || (_lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address)); - } - - /// - public bool IsPrivateAddressRange(IPObject address) - { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } - - // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. - if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) - { - return true; - } - else - { - return address.IsPrivateAddressRange(); - } - } - - /// - public bool IsExcludedInterface(IPAddress address) - { - return _bindExclusions.ContainsAddress(address); - } - - /// - public Collection GetFilteredLANSubnets(Collection? filter = null) - { - if (filter == null) - { - return _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks(); - } - - return _lanSubnets.Exclude(filter, true); - } - - /// - public bool IsValidInterfaceAddress(IPAddress address) - { - return _interfaceAddresses.ContainsAddress(address); - } - - /// - public bool TryParseInterface(string token, out Collection? result) - { - result = null; - if (string.IsNullOrEmpty(token)) - { - return false; - } - - if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index)) - { - result = new Collection(); - - _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); - - // Replace interface tags with the interface IP's. - foreach (IPNetAddress iface in _interfaceAddresses) - { - if (Math.Abs(iface.Tag) == index - && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) - || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) - { - result.AddItem(iface, false); - } - } - - return true; - } - - return false; - } - - /// - 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.Count > 0 && !IsInLocalNetwork(remoteIp)) - { - // remoteAddressFilter is a whitelist or blacklist. - return RemoteAddressFilter.ContainsAddress(remoteIp) == !config.IsRemoteIPFilterBlacklist; - } - } - else if (!IsInLocalNetwork(remoteIp)) - { - // Remote not enabled. So everyone should be LAN. - return false; - } - - return true; - } - - /// - /// Reloads all settings and re-initialises the instance. - /// - /// The to use. - public void UpdateSettings(object configuration) - { - NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); - - IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4; - IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6; - - if (!IsIP6Enabled && !IsIP4Enabled) - { - _logger.LogError("IPv4 and IPv6 cannot both be disabled."); - IsIP4Enabled = true; - } - - TrustAllIP6Interfaces = config.TrustAllIP6Interfaces; - - if (string.IsNullOrEmpty(MockNetworkSettings)) - { - InitialiseInterfaces(); - } - else // Used in testing only. - { - // Format is ,,: . Set index to -ve to simulate a gateway. - var interfaceList = MockNetworkSettings.Split('|'); - foreach (var details in interfaceList) - { - var parts = details.Split(','); - var address = IPNetAddress.Parse(parts[0]); - var index = int.Parse(parts[1], CultureInfo.InvariantCulture); - address.Tag = index; - _interfaceAddresses.AddItem(address, false); - _interfaceNames[parts[2]] = Math.Abs(index); - } - } - - InitialiseLAN(config); - InitialiseBind(config); - InitialiseRemote(config); - InitialiseOverrides(config); - } - - /// - /// Protected implementation of Dispose pattern. - /// - /// True to dispose the managed state. - protected virtual void Dispose(bool disposing) - { - if (!_disposed) - { - if (disposing) - { - _configurationManager.NamedConfigurationUpdated -= ConfigurationUpdated; - NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged; - NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged; - } - - _disposed = true; - } - } - - /// - /// Tries to identify the string and return an object of that class. - /// - /// String to parse. - /// IPObject to return. - /// true if the value parsed successfully, false otherwise. - private static bool TryParse(string addr, out IPObject result) - { - if (!string.IsNullOrEmpty(addr)) - { - // Is it an IP address - if (IPNetAddress.TryParse(addr, out IPNetAddress nw)) - { - result = nw; - return true; - } - - if (IPHost.TryParse(addr, out IPHost h)) - { - result = h; - return true; - } - } - - result = IPNetAddress.None; - return false; - } - - /// - /// Converts an IPAddress into a string. - /// Ipv6 addresses are returned in [ ], with their scope removed. - /// - /// Address to convert. - /// URI safe conversion of the address. - private static string FormatIP6String(IPAddress address) - { - var str = address.ToString(); - if (address.AddressFamily == AddressFamily.InterNetworkV6) - { - int i = str.IndexOf("%", StringComparison.OrdinalIgnoreCase); - if (i != -1) - { - str = str.Substring(0, i); - } - - return $"[{str}]"; - } - - return str; - } - - private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) - { - if (evt.Key.Equals(NetworkConfigurationStore.StoreKey, StringComparison.Ordinal)) - { - UpdateSettings((NetworkConfiguration)evt.NewConfiguration); - } - } - - /// - /// Checks the string to see if it matches any interface names. - /// - /// String to check. - /// Interface index numbers that match. - /// true if an interface name matches the token, False otherwise. - private bool TryGetInterfaces(string token, [NotNullWhen(true)] out List? index) - { - index = null; - - // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. - // Null check required here for automated testing. - if (_interfaceNames != null && token.Length > 1) - { - bool partial = token[^1] == '*'; - if (partial) - { - token = token[..^1]; - } - - foreach ((string interfc, int interfcIndex) in _interfaceNames) - { - if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) - || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) - { - index ??= new List(); - index.Add(interfcIndex); - } - } - } - - return index != null; - } - - /// - /// Parses a string and adds it into the collection, replacing any interface references. - /// - /// Collection. - /// String value to parse. - private void AddToCollection(Collection col, string token) - { - // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. - // Null check required here for automated testing. - if (TryGetInterfaces(token, out var indices)) - { - _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token); - - // Replace all the interface tags with the interface IP's. - foreach (IPNetAddress iface in _interfaceAddresses) - { - if (indices.Contains(Math.Abs(iface.Tag)) - && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) - || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) - { - col.AddItem(iface); - } - } - } - else if (TryParse(token, out IPObject obj)) - { - // Expand if the ip address is "any". - if ((obj.Address.Equals(IPAddress.Any) && IsIP4Enabled) - || (obj.Address.Equals(IPAddress.IPv6Any) && IsIP6Enabled)) - { - foreach (IPNetAddress iface in _interfaceAddresses) - { - if (obj.AddressFamily == iface.AddressFamily) - { - col.AddItem(iface); - } - } - } - else if (!IsIP6Enabled) - { - // Remove IP6 addresses from multi-homed IPHosts. - obj.Remove(AddressFamily.InterNetworkV6); - if (!obj.IsIP6()) - { - col.AddItem(obj); - } - } - else if (!IsIP4Enabled) - { - // Remove IP4 addresses from multi-homed IPHosts. - obj.Remove(AddressFamily.InterNetwork); - if (obj.IsIP6()) - { - col.AddItem(obj); - } - } - else - { - col.AddItem(obj); - } - } - else - { - _logger.LogDebug("Invalid or unknown object {Token}.", token); - } - } - /// /// Handler for network change events. /// @@ -838,27 +165,6 @@ namespace Jellyfin.Networking.Manager OnNetworkChanged(); } - /// - /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. - /// - /// A representing the asynchronous operation. - private async Task OnNetworkChangeAsync() - { - try - { - await Task.Delay(2000).ConfigureAwait(false); - InitialiseInterfaces(); - // Recalculate LAN caches. - InitialiseLAN(_configurationManager.GetNetworkConfiguration()); - - NetworkChanged?.Invoke(this, EventArgs.Empty); - } - finally - { - _eventfire = false; - } - } - /// /// Triggers our event, and re-loads interface information. /// @@ -877,160 +183,23 @@ namespace Jellyfin.Networking.Manager } /// - /// Parses the user defined overrides into the dictionary object. - /// Overrides are the equivalent of localised publishedServerUrl, enabling - /// different addresses to be advertised over different subnets. - /// format is subnet=ipaddress|host|uri - /// when subnet = 0.0.0.0, any external address matches. + /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. /// - private void InitialiseOverrides(NetworkConfiguration config) + /// A representing the asynchronous operation. + private async Task OnNetworkChangeAsync() { - lock (_intLock) + try { - _publishedServerUrls.Clear(); - string[] overrides = config.PublishedServerUriBySubnet; - if (overrides == null) - { - return; - } + await Task.Delay(2000).ConfigureAwait(false); + InitialiseInterfaces(); + // Recalculate LAN caches. + InitialiseLan(_configurationManager.GetNetworkConfiguration()); - foreach (var entry in overrides) - { - var parts = entry.Split('='); - if (parts.Length != 2) - { - _logger.LogError("Unable to parse bind override: {Entry}", entry); - } - else - { - var replacement = parts[1].Trim(); - if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase)) - { - _publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement; - } - else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase)) - { - _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement; - } - else if (TryParseInterface(parts[0], out Collection? addresses) && addresses != null) - { - foreach (IPNetAddress na in addresses) - { - _publishedServerUrls[na] = replacement; - } - } - else if (IPNetAddress.TryParse(parts[0], out IPNetAddress result)) - { - _publishedServerUrls[result] = replacement; - } - else - { - _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]); - } - } - } + NetworkChanged?.Invoke(this, EventArgs.Empty); } - } - - /// - /// Initialises the network bind addresses. - /// - private void InitialiseBind(NetworkConfiguration config) - { - lock (_intLock) + finally { - string[] lanAddresses = config.LocalNetworkAddresses; - - // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded. - if (config.IgnoreVirtualInterfaces) - { - // each virtual interface name must be pre-pended with the exclusion symbol ! - var virtualInterfaceNames = config.VirtualInterfaceNames.Split(',').Select(p => "!" + p).ToArray(); - if (lanAddresses.Length > 0) - { - var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length]; - Array.Copy(lanAddresses, newList, lanAddresses.Length); - Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length); - lanAddresses = newList; - } - else - { - lanAddresses = virtualInterfaceNames; - } - } - - // Read and parse bind addresses and exclusions, removing ones that don't exist. - _bindAddresses = CreateIPCollection(lanAddresses).ThatAreContainedInNetworks(_interfaceAddresses); - _bindExclusions = CreateIPCollection(lanAddresses, true).ThatAreContainedInNetworks(_interfaceAddresses); - _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString()); - _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString()); - } - } - - /// - /// Initialises the remote address values. - /// - private void InitialiseRemote(NetworkConfiguration config) - { - lock (_intLock) - { - RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter); - } - } - - /// - /// Initialises internal LAN cache settings. - /// - private void InitialiseLAN(NetworkConfiguration config) - { - lock (_intLock) - { - _logger.LogDebug("Refreshing LAN information."); - - // Get configuration options. - string[] subnets = config.LocalNetworkSubnets; - - // Create lists from user settings. - - _lanSubnets = CreateIPCollection(subnets); - _excludedSubnets = CreateIPCollection(subnets, true).AsNetworks(); - - // If no LAN addresses are specified - all private subnets are deemed to be the LAN - _usingPrivateAddresses = _lanSubnets.Count == 0; - - // NOTE: The order of the commands generating the collection in this statement matters. - // Altering the order will cause the collections to be created incorrectly. - if (_usingPrivateAddresses) - { - _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); - // Internal interfaces must be private and not excluded. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i))); - - // Subnets are the same as the calculated internal interface. - _lanSubnets = new Collection(); - - if (IsIP6Enabled) - { - _lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA - _lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local - } - - if (IsIP4Enabled) - { - _lanSubnets.AddItem(IPNetAddress.Parse("10.0.0.0/8")); - _lanSubnets.AddItem(IPNetAddress.Parse("172.16.0.0/12")); - _lanSubnets.AddItem(IPNetAddress.Parse("192.168.0.0/16")); - } - } - else - { - // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet. - _internalInterfaces = CreateCollection(_interfaceAddresses.Where(IsInLocalNetwork)); - } - - _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.AsString()); - _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets.AsString()); - _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks().AsString()); + _eventfire = false; } } @@ -1040,12 +209,11 @@ namespace Jellyfin.Networking.Manager /// private void InitialiseInterfaces() { - lock (_intLock) + lock (_initLock) { _logger.LogDebug("Refreshing interfaces."); - _interfaceNames.Clear(); - _interfaceAddresses.Clear(); + _interfaces.Clear(); _macAddresses.Clear(); try @@ -1060,136 +228,800 @@ namespace Jellyfin.Networking.Manager IPInterfaceProperties ipProperties = adapter.GetIPProperties(); PhysicalAddress mac = adapter.GetPhysicalAddress(); - // populate mac list - if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac != null && mac != PhysicalAddress.None) + // Populate MAC list + if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && PhysicalAddress.None.Equals(mac)) { _macAddresses.Add(mac); } - // populate interface address list + // Populate interface list foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses) { - if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) + if (IsIpv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) { - IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask)) - { - // Keep the number of gateways on this interface, along with its index. - Tag = ipProperties.GetIPv4Properties().Index - }; + 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); - int tag = nw.Tag; - if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) - { - // -ve Tags signify the interface has a gateway. - nw.Tag *= -1; - } - - _interfaceAddresses.AddItem(nw, false); - - // Store interface name so we can use the name in Collections. - _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; - _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; + _interfaces.Add(interfaceObject); } - else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) + else if (IsIpv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) { - IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength) - { - // Keep the number of gateways on this interface, along with its index. - Tag = ipProperties.GetIPv6Properties().Index - }; + 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); - int tag = nw.Tag; - if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback()) - { - // -ve Tags signify the interface has a gateway. - nw.Tag *= -1; - } - - _interfaceAddresses.AddItem(nw, false); - - // Store interface name so we can use the name in Collections. - _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag; - _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag; + _interfaces.Add(interfaceObject); } } } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) +#pragma warning restore CA1031 // Do not catch general exception types { // Ignore error, and attempt to continue. _logger.LogError(ex, "Error encountered parsing interfaces."); } -#pragma warning restore CA1031 // Do not catch general exception types } } +#pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) +#pragma warning restore CA1031 // Do not catch general exception types { - _logger.LogError(ex, "Error in InitialiseInterfaces."); + _logger.LogError(ex, "Error obtaining interfaces."); } - // If for some reason we don't have an interface info, resolve our DNS name. - if (_interfaceAddresses.Count == 0) + // 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."); - IPHost host = new IPHost(Dns.GetHostName()); - foreach (var a in host.GetAddresses()) + var hostName = Dns.GetHostName(); + if (Uri.CheckHostName(hostName).Equals(UriHostNameType.Dns)) { - _interfaceAddresses.AddItem(a); + 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 (_interfaceAddresses.Count == 0) + if (_interfaces.Count == 0) { _logger.LogWarning("No interfaces information available. Using loopback."); } } - if (IsIP4Enabled) + if (IsIpv4Enabled && !IsIpv6Enabled) { - _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback); + _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); } - if (IsIP6Enabled) + if (!IsIpv4Enabled && IsIpv6Enabled) { - _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback); + _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); } - _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count); - _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses.AsString()); + _logger.LogDebug("Discovered {0} interfaces.", _interfaces.Count); + _logger.LogDebug("Interfaces addresses : {0}", _interfaces.Select(s => s.Address).ToString()); } } /// - /// Attempts to match the source against a user defined bind interface. + /// Initialises internal LAN cache. + /// + private void InitialiseLan(NetworkConfiguration config) + { + lock (_initLock) + { + _logger.LogDebug("Refreshing LAN information."); + + // Get configuration options + string[] subnets = config.LocalNetworkSubnets; + + _ = TryParseSubnets(subnets, out _lanSubnets, false); + _ = TryParseSubnets(subnets, out _excludedSubnets, true); + + if (_lanSubnets.Count == 0) + { + // If no LAN addresses are specified, all private subnets are deemed to be the LAN + _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); + + if (IsIpv6Enabled) + { + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // ULA + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // Site local + } + + if (IsIpv4Enabled) + { + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("172.16.0.0"), 12)); + _lanSubnets.Add(new IPNetwork(IPAddress.Parse("192.168.0.0"), 16)); + } + } + + _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)); + } + } + + /// + /// Initialises the network bind addresses. + /// + private void InitialiseBind(NetworkConfiguration config) + { + lock (_initLock) + { + // Use explicit bind addresses + if (config.LocalNetworkAddresses.Length > 0) + { + _bindAddresses = config.LocalNetworkAddresses.Select(p => IPAddress.TryParse(p, out var address) + ? address + : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)).Select(x => x.Address).FirstOrDefault() ?? IPAddress.None)).ToList(); + _bindAddresses.RemoveAll(x => x == IPAddress.None); + } + 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 + if (config.IgnoreVirtualInterfaces) + { + // Remove potentially exisiting * and split config string into prefixes + var virtualInterfacePrefixes = config.VirtualInterfaceNames.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase).ToLower().Split(','); + + // Check all interfaces for matches against the prefixes and add the interface IPs to _bindExclusions + if (_bindAddresses.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); + } + } + } + } + + // 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); + } + } + + /// + /// Initialises the remote address values. + /// + private void InitialiseRemote(NetworkConfiguration config) + { + lock (_initLock) + { + // Parse config values into filter collection + var remoteIPFilter = config.RemoteIPFilter; + if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First())) + { + // Parse all IPs with netmask to a subnet + _ = 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)); + foreach (var ip in ips) + { + if (IPAddress.TryParse(ip, out var ipp)) + { + _remoteAddressFilter.Add(new IPNetwork(ipp, ipp.AddressFamily == AddressFamily.InterNetwork ? 32 : 128)); + } + } + } + } + } + + /// + /// Parses the user defined overrides into the dictionary object. + /// Overrides are the equivalent of localised publishedServerUrl, enabling + /// different addresses to be advertised over different subnets. + /// format is subnet=ipaddress|host|uri + /// when subnet = 0.0.0.0, any external address matches. + /// + private void InitialiseOverrides(NetworkConfiguration config) + { + lock (_initLock) + { + _publishedServerUrls.Clear(); + string[] overrides = config.PublishedServerUriBySubnet; + + foreach (var entry in overrides) + { + var parts = entry.Split('='); + if (parts.Length != 2) + { + _logger.LogError("Unable to parse bind override: {Entry}", entry); + } + else + { + var replacement = parts[1].Trim(); + var ipParts = parts[0].Split("/"); + if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase)) + { + _publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement; + } + else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase)) + { + _publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement; + _publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement; + } + else if (IPAddress.TryParse(ipParts[0], out IPAddress? result)) + { + var data = new IPData(result, null); + if (ipParts.Length > 1 && int.TryParse(ipParts[1], out var netmask)) + { + data.Subnet = new IPNetwork(result, netmask); + } + + _publishedServerUrls[data] = replacement; + } + else if (TryParseInterface(parts[0], out var ifaces)) + { + foreach (var iface in ifaces) + { + _publishedServerUrls[iface] = replacement; + } + } + else + { + _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]); + } + } + } + } + } + + private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) + { + if (evt.Key.Equals("network", StringComparison.Ordinal)) + { + UpdateSettings((NetworkConfiguration)evt.NewConfiguration); + } + } + + /// + /// Reloads all settings and re-initialises the instance. + /// + /// The to use. + public void UpdateSettings(object configuration) + { + NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); + + if (string.IsNullOrEmpty(MockNetworkSettings)) + { + InitialiseInterfaces(); + } + else // Used in testing only. + { + // Format is ,,: . Set index to -ve to simulate a gateway. + var interfaceList = MockNetworkSettings.Split('|'); + foreach (var details in interfaceList) + { + var parts = details.Split(','); + var split = parts[0].Split("/"); + var address = IPAddress.Parse(split[0]); + var network = new IPNetwork(address, int.Parse(split[1], CultureInfo.InvariantCulture)); + var index = int.Parse(parts[1], CultureInfo.InvariantCulture); + if (address.AddressFamily == AddressFamily.InterNetwork) + { + _interfaces.Add(new IPData(address, network, parts[2])); + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + _interfaces.Add(new IPData(address, network, parts[2])); + } + } + } + + InitialiseLan(config); + InitialiseBind(config); + InitialiseRemote(config); + InitialiseOverrides(config); + } + + /// + /// Protected implementation of Dispose pattern. + /// + /// True to dispose the managed state. + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + _configurationManager.NamedConfigurationUpdated -= ConfigurationUpdated; + NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged; + NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged; + } + + _disposed = true; + } + } + + /// + public bool TryParseInterface(string intf, out Collection result) + { + result = new Collection(); + if (string.IsNullOrEmpty(intf)) + { + return false; + } + + 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)); + if (matchedInterfaces.Any()) + { + _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", intf); + + // Use interface IP instead of name + foreach (IPData iface in matchedInterfaces) + { + if ((IsIpv4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIpv6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)) + { + result.Add(iface); + } + } + + return true; + } + } + + return false; + } + + /// + /// Try parsing an array of strings into subnets, respecting exclusions. + /// + /// Input string to be parsed. + /// Collection of . + /// Boolean signaling if negated or not negated values should be parsed. + /// True if parsing was successful. + public bool TryParseSubnets(string[] values, out Collection result, bool negated = false) + { + result = new Collection(); + + if (values == null || values.Length == 0) + { + return false; + } + + for (int a = 0; a < values.Length; a++) + { + string[] v = values[a].Trim().Split("/"); + + try + { + var address = IPAddress.None; + if (negated && v[0].StartsWith('!')) + { + _ = IPAddress.TryParse(v[0][1..], out address); + } + else if (!negated) + { + _ = IPAddress.TryParse(v[0][0..], out address); + } + + if (address != IPAddress.None && address != null) + { + if (int.TryParse(v[1], out var netmask)) + { + result.Add(new IPNetwork(address, netmask)); + } + else if (address.AddressFamily == AddressFamily.InterNetwork) + { + result.Add(new IPNetwork(address, 32)); + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + result.Add(new IPNetwork(address, 128)); + } + } + } + catch (ArgumentException e) + { + _logger.LogWarning(e, "Ignoring LAN value {Value}.", v); + } + } + + if (result.Count > 0) + { + return true; + } + + return false; + } + + /// + public bool HasRemoteAccess(IPAddress remoteIp) + { + 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))) + { + // remoteAddressFilter is a whitelist or blacklist. + var matches = _remoteAddressFilter.Count(remoteNetwork => remoteNetwork.Contains(remoteIp)); + if ((!config.IsRemoteIPFilterBlacklist && matches > 0) + || (config.IsRemoteIPFilterBlacklist && matches == 0)) + { + return true; + } + + return false; + } + } + else if (!_lanSubnets.Where(x => x.Contains(remoteIp)).Any()) + { + // Remote not enabled. So everyone should be LAN. + return false; + } + + return true; + } + + /// + public IReadOnlyCollection GetMacAddresses() + { + // Populated in construction - so always has values. + return _macAddresses; + } + + /// + public List GetLoopbacks() + { + var loopbackNetworks = new List(); + if (IsIpv4Enabled) + { + loopbackNetworks.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo")); + } + + if (IsIpv6Enabled) + { + loopbackNetworks.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo")); + } + + return loopbackNetworks; + } + + /// + public List GetAllBindInterfaces(bool individualInterfaces = false) + { + if (_bindAddresses.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(); + + if (individualInterfaces) + { + foreach (var iface in _interfaces) + { + result.Add(iface); + } + + return result; + } + + 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) + { + result.Add(new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))); + } + else if (IsIpv6Enabled) + { + // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too. + foreach (var iface in _interfaces) + { + if (iface.AddressFamily == AddressFamily.InterNetworkV6) + { + result.Add(iface); + } + } + } + + 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(); + } + + /// + public string GetBindInterface(string source, out int? port) + { + _ = NetworkExtensions.TryParseHost(source, out var address, IsIpv4Enabled, IsIpv6Enabled); + var result = GetBindInterface(address.FirstOrDefault(), out port); + return result; + } + + /// + public string GetBindInterface(HttpRequest source, out int? port) + { + string result; + _ = NetworkExtensions.TryParseHost(source.Host.Host, out var addresses, IsIpv4Enabled, IsIpv6Enabled); + result = GetBindInterface(addresses.FirstOrDefault(), out port); + port ??= source.Host.Port; + + return result; + } + + /// + public string GetBindInterface(IPAddress? source, out int? port) + { + port = null; + + string result; + + if (source != null) + { + if (IsIpv4Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) + { + _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); + } + + if (IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) + { + _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected."); + } + + bool isExternal = !_lanSubnets.Any(network => network.Contains(source)); + _logger.LogDebug("GetBindInterface with source. External: {IsExternal}:", isExternal); + + if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) + { + _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port); + return res; + } + + // No preference given, so move on to bind addresses. + if (MatchesBindInterface(source, isExternal, out result)) + { + return result; + } + + if (isExternal && MatchesExternalInterface(source, out result)) + { + return result; + } + } + + // 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)) + .ThenBy(x => x.Index); + + if (availableInterfaces.Any()) + { + if (source != null) + { + foreach (var intf in availableInterfaces) + { + if (intf.Address.Equals(source)) + { + result = NetworkExtensions.FormatIpString(intf.Address); + _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface. {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) + { + 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); + return result; + } + } + } + + result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address); + _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result); + return result; + } + + // There isn't any others, so we'll use the loopback. + result = IsIpv4Enabled && !IsIpv6Enabled ? "127.0.0.1" : "::1"; + _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result); + return result; + } + + /// + public List 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)) + .OrderBy(x => x.Index).ToList(); + } + + /// + public bool IsInLocalNetwork(string address) + { + if (IPAddress.TryParse(address, out var ep)) + { + return IPAddress.IsLoopback(ep) || (_lanSubnets.Any(x => x.Contains(ep)) && !_excludedSubnets.Any(x => x.Contains(ep))); + } + + 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))); + } + + return match; + } + + return false; + } + + /// + public bool IsInLocalNetwork(IPAddress address) + { + if (address == null) + { + throw new ArgumentNullException(nameof(address)); + } + + // See conversation at https://github.com/jellyfin/jellyfin/pull/3515. + if (TrustAllIpv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) + { + return true; + } + + // As private addresses can be redefined by Configuration.LocalNetworkAddresses + var match = CheckIfLanAndNotExcluded(address); + + 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; + foreach (var lanSubnet in _lanSubnets) + { + match |= lanSubnet.Contains(address); + } + + foreach (var excludedSubnet in _excludedSubnets) + { + match &= !excludedSubnet.Contains(address); + } + + NetworkExtensions.IsIPv6LinkLocal(address); + return match; + } + + /// + /// Attempts to match the source against the published server URL overrides. /// /// IP source address to use. - /// True if the source is in the external subnet. - /// The published server url that matches the source address. + /// True if the source is in an external subnet. + /// The published server URL that matches the source address. /// The resultant port, if one exists. /// true if a match is found, false otherwise. - private bool MatchesPublishedServerUrl(IPObject source, bool isInExternalSubnet, out string bindPreference, out int? port) + private bool MatchesPublishedServerUrl(IPAddress source, bool isInExternalSubnet, out string bindPreference, out int? port) { bindPreference = string.Empty; port = null; + var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any)).ToList(); + validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.IPv6Any))); + validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Subnet.Contains(source))); + validPublishedServerUrls.Distinct(); + // Check for user override. - foreach (var addr in _publishedServerUrls) + foreach (var data in validPublishedServerUrls) { + // Get address interface + var intf = _interfaces.FirstOrDefault(s => s.Subnet.Contains(data.Key.Address)); + // Remaining. Match anything. - if (addr.Key.Address.Equals(IPAddress.Broadcast)) + if (data.Key.Address.Equals(IPAddress.Broadcast)) { - bindPreference = addr.Value; + bindPreference = data.Value; break; } - else if ((addr.Key.Address.Equals(IPAddress.Any) || addr.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet) + else if ((data.Key.Address.Equals(IPAddress.Any) || data.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet) { // External. - bindPreference = addr.Value; + bindPreference = data.Value; break; } - else if (addr.Key.Contains(source)) + else if (intf?.Address != null) { // Match ip address. - bindPreference = addr.Value; + bindPreference = data.Value; break; } } @@ -1220,12 +1052,11 @@ namespace Jellyfin.Networking.Manager /// True if the source is in the external subnet. /// The result, if a match is found. /// true if a match is found, false otherwise. - private bool MatchesBindInterface(IPObject source, bool isInExternalSubnet, out string result) + private bool MatchesBindInterface(IPAddress source, bool isInExternalSubnet, out string result) { result = string.Empty; - var addresses = _bindAddresses.Exclude(_bindExclusions, false); - int count = addresses.Count; + int count = _bindAddresses.Count; if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any))) { // Ignore IPAny addresses. @@ -1234,24 +1065,25 @@ namespace Jellyfin.Networking.Manager if (count != 0) { - // Check to see if any of the bind interfaces are in the same subnet. - + // Check to see if any of the bind interfaces are in the same subnet as the source. IPAddress? defaultGateway = null; IPAddress? bindAddress = null; if (isInExternalSubnet) { // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first. - foreach (var addr in addresses.OrderBy(p => p.Tag)) + foreach (var addr in _bindAddresses) { if (defaultGateway == null && !IsInLocalNetwork(addr)) { - defaultGateway = addr.Address; + defaultGateway = addr; } - if (bindAddress == null && addr.Contains(source)) + var intf = _interfaces.Where(x => x.Subnet.Contains(addr)).FirstOrDefault(); + + if (bindAddress == null && intf != null && intf.Subnet.Contains(source)) { - bindAddress = addr.Address; + bindAddress = intf.Address; } if (defaultGateway != null && bindAddress != null) @@ -1263,32 +1095,37 @@ namespace Jellyfin.Networking.Manager else { // Look for the best internal address. - bindAddress = addresses - .Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None))) - .OrderBy(p => p.Tag) - .FirstOrDefault()?.Address; + foreach (var bA in _bindAddresses.Where(x => IsInLocalNetwork(x))) + { + var intf = FindInterfaceForIp(source, true); + if (intf != null) + { + bindAddress = intf.Address; + break; + } + } } if (bindAddress != null) { - result = FormatIP6String(bindAddress); - _logger.LogDebug("{Source}: GetBindInterface: Has source, found a match bind interface subnets. {Result}", source, result); + 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 = FormatIP6String(defaultGateway); + result = NetworkExtensions.FormatIpString(defaultGateway); _logger.LogDebug("{Source}: GetBindInterface: Using first user defined external interface. {Result}", source, result); return true; } - result = FormatIP6String(addresses[0].Address); + 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, however, only an internal interface bind found.", source); + _logger.LogWarning("{Source}: External request received, only an internal interface bind found.", source); } return true; @@ -1303,30 +1140,29 @@ namespace Jellyfin.Networking.Manager /// IP source address to use. /// The result, if a match is found. /// true if a match is found, false otherwise. - private bool MatchesExternalInterface(IPObject source, out string result) + private bool MatchesExternalInterface(IPAddress source, out string result) { result = string.Empty; // Get the first WAN interface address that isn't a loopback. - var extResult = _interfaceAddresses - .Exclude(_bindExclusions, false) - .Where(p => !IsInLocalNetwork(p)) - .OrderBy(p => p.Tag); + var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address)); - if (extResult.Any()) + IPAddress? hasResult = null; + // Does the request originate in one of the interface subnets? + // (For systems with multiple internal network cards, and multiple subnets) + foreach (var intf in extResult) { - // Does the request originate in one of the interface subnets? - // (For systems with multiple internal network cards, and multiple subnets) - foreach (var intf in extResult) + hasResult ??= intf.Address; + if (!IsInLocalNetwork(intf.Address) && intf.Subnet.Contains(source)) { - if (!IsInLocalNetwork(intf) && intf.Contains(source)) - { - result = FormatIP6String(intf.Address); - _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range. {Result}", source, result); - return true; - } + result = NetworkExtensions.FormatIpString(intf.Address); + _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range. {Result}", source, result); + return true; } + } - result = FormatIP6String(extResult.First().Address); + if (hasResult != null) + { + result = NetworkExtensions.FormatIpString(hasResult); _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface. {Result}", source, result); return true; } diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index 66fa3bc31b..7030b726cd 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -344,13 +344,13 @@ namespace Jellyfin.Server.Extensions { for (var i = 0; i < allowedProxies.Length; i++) { - if (IPNetAddress.TryParse(allowedProxies[i], out var addr)) + if (IPAddress.TryParse(allowedProxies[i], out var addr)) { - AddIpAddress(config, options, addr.Address, addr.PrefixLength); + AddIpAddress(config, options, addr, addr.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } - else if (IPHost.TryParse(allowedProxies[i], out var host)) + else if (NetworkExtensions.TryParseHost(allowedProxies[i], out var host)) { - foreach (var address in host.GetAddresses()) + foreach (var address in host) { AddIpAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); } diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs index 5e601ca847..ceeaa26e62 100644 --- a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs +++ b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs @@ -114,9 +114,7 @@ public class CreateNetworkConfiguration : IMigrationRoutine public bool IgnoreVirtualInterfaces { get; set; } = true; - public string VirtualInterfaceNames { get; set; } = "vEthernet*"; - - public bool TrustAllIP6Interfaces { get; set; } + public string VirtualInterfaceNames { get; set; } = "veth*"; public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 2bda8d2905..63055a61d4 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -300,7 +300,7 @@ namespace Jellyfin.Server var addresses = appHost.NetManager.GetAllBindInterfaces(); bool flagged = false; - foreach (IPObject netAdd in addresses) + foreach (IPData netAdd in addresses) { _logger.LogInformation("Kestrel listening on {Address}", netAdd.Address == IPAddress.IPv6Any ? "All Addresses" : netAdd); options.Listen(netAdd.Address, appHost.HttpPort); @@ -689,10 +689,10 @@ namespace Jellyfin.Server if (!string.IsNullOrEmpty(socketPerms)) { - #pragma warning disable SA1300 // Entrypoint is case sensitive. +#pragma warning disable SA1300 // Entrypoint is case sensitive. [DllImport("libc")] static extern int chmod(string pathname, int mode); - #pragma warning restore SA1300 +#pragma warning restore SA1300 var exitCode = chmod(socketPath, Convert.ToInt32(socketPerms, 8)); diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index b939397301..fdf42bdbce 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. diff --git a/MediaBrowser.Common/Net/IPData.cs b/MediaBrowser.Common/Net/IPData.cs new file mode 100644 index 0000000000..3c6adc7e86 --- /dev/null +++ b/MediaBrowser.Common/Net/IPData.cs @@ -0,0 +1,76 @@ +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. + /// + /// An . + /// The . + public IPData( + IPAddress address, + IPNetwork? subnet) + { + Address = address; + Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128)); + Name = string.Empty; + } + + /// + /// Initializes a new instance of the class. + /// + /// An . + /// The . + /// The object's name. + public IPData( + IPAddress address, + IPNetwork? subnet, + string name) + { + Address = address; + Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128)); + Name = name; + } + + /// + /// 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 this object. + /// + public AddressFamily AddressFamily + { + get + { + return Address.Equals(IPAddress.None) + ? (Subnet.Prefix.AddressFamily.Equals(IPAddress.None) + ? AddressFamily.Unspecified : Subnet.Prefix.AddressFamily) + : Address.AddressFamily; + } + } + } +} diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs deleted file mode 100644 index 1f125f2b1d..0000000000 --- a/MediaBrowser.Common/Net/IPHost.cs +++ /dev/null @@ -1,441 +0,0 @@ -using System; -using System.Diagnostics; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Text.RegularExpressions; - -namespace MediaBrowser.Common.Net -{ - /// - /// Object that holds a host name. - /// - public class IPHost : IPObject - { - /// - /// Gets or sets timeout value before resolve required, in minutes. - /// - public const int Timeout = 30; - - /// - /// Represents an IPHost that has no value. - /// - public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None); - - /// - /// Time when last resolved in ticks. - /// - private DateTime? _lastResolved = null; - - /// - /// Gets the IP Addresses, attempting to resolve the name, if there are none. - /// - private IPAddress[] _addresses; - - /// - /// Initializes a new instance of the class. - /// - /// Host name to assign. - public IPHost(string name) - { - HostName = name ?? throw new ArgumentNullException(nameof(name)); - _addresses = Array.Empty(); - Resolved = false; - } - - /// - /// Initializes a new instance of the class. - /// - /// Host name to assign. - /// Address to assign. - private IPHost(string name, IPAddress address) - { - HostName = name ?? throw new ArgumentNullException(nameof(name)); - _addresses = new IPAddress[] { address ?? throw new ArgumentNullException(nameof(address)) }; - Resolved = !address.Equals(IPAddress.None); - } - - /// - /// Gets or sets the object's first IP address. - /// - public override IPAddress Address - { - get - { - return ResolveHost() ? this[0] : IPAddress.None; - } - - set - { - // Not implemented, as a host's address is determined by DNS. - throw new NotImplementedException("The address of a host is determined by DNS."); - } - } - - /// - /// Gets or sets the object's first IP's subnet prefix. - /// The setter does nothing, but shouldn't raise an exception. - /// - public override byte PrefixLength - { - get => (byte)(ResolveHost() ? 128 : 32); - - // Not implemented, as a host object can only have a prefix length of 128 (IPv6) or 32 (IPv4) prefix length, - // which is automatically determined by it's IP type. Anything else is meaningless. - set => throw new NotImplementedException(); - } - - /// - /// Gets a value indicating whether the address has a value. - /// - public bool HasAddress => _addresses.Length != 0; - - /// - /// Gets the host name of this object. - /// - public string HostName { get; } - - /// - /// Gets a value indicating whether this host has attempted to be resolved. - /// - public bool Resolved { get; private set; } - - /// - /// Gets or sets the IP Addresses associated with this object. - /// - /// Index of address. - public IPAddress this[int index] - { - get - { - ResolveHost(); - return index >= 0 && index < _addresses.Length ? _addresses[index] : IPAddress.None; - } - } - - /// - /// Attempts to parse the host string. - /// - /// Host name to parse. - /// Object representing the string, if it has successfully been parsed. - /// true if the parsing is successful, false if not. - public static bool TryParse(string host, out IPHost hostObj) - { - if (string.IsNullOrWhiteSpace(host)) - { - hostObj = IPHost.None; - return false; - } - - // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. - int i = host.IndexOf(']', StringComparison.Ordinal); - if (i != -1) - { - return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); - } - - if (IPNetAddress.TryParse(host, out var netAddress)) - { - // Host name is an ip address, so fake resolve. - hostObj = new IPHost(host, netAddress.Address); - return true; - } - - // Is it a host, IPv4/6 with/out port? - string[] hosts = host.Split(':'); - - if (hosts.Length <= 2) - { - // This is either a hostname: port, or an IP4:port. - host = hosts[0]; - - if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase)) - { - hostObj = new IPHost(host); - return true; - } - - if (IPAddress.TryParse(host, out var netIP)) - { - // Host name is an ip address, so fake resolve. - hostObj = new IPHost(host, netIP); - return true; - } - } - else - { - // Invalid host name, as it cannot contain : - hostObj = new IPHost(string.Empty, IPAddress.None); - return false; - } - - // Use regular expression as CheckHostName isn't RFC5892 compliant. - // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation - string pattern = @"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$"; - - if (Regex.IsMatch(host, pattern)) - { - hostObj = new IPHost(host); - return true; - } - - hostObj = IPHost.None; - return false; - } - - /// - /// Attempts to parse the host string. - /// - /// Host name to parse. - /// Object representing the string, if it has successfully been parsed. - public static IPHost Parse(string host) - { - if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res)) - { - return res; - } - - throw new InvalidCastException($"Host does not contain a valid value. {host}"); - } - - /// - /// Attempts to parse the host string, ensuring that it resolves only to a specific IP type. - /// - /// Host name to parse. - /// Addressfamily filter. - /// Object representing the string, if it has successfully been parsed. - public static IPHost Parse(string host, AddressFamily family) - { - if (!string.IsNullOrEmpty(host) && IPHost.TryParse(host, out IPHost res)) - { - if (family == AddressFamily.InterNetwork) - { - res.Remove(AddressFamily.InterNetworkV6); - } - else - { - res.Remove(AddressFamily.InterNetwork); - } - - return res; - } - - throw new InvalidCastException($"Host does not contain a valid value. {host}"); - } - - /// - /// Returns the Addresses that this item resolved to. - /// - /// IPAddress Array. - public IPAddress[] GetAddresses() - { - ResolveHost(); - return _addresses; - } - - /// - public override bool Contains(IPAddress address) - { - if (address != null && !Address.Equals(IPAddress.None)) - { - if (address.IsIPv4MappedToIPv6) - { - address = address.MapToIPv4(); - } - - foreach (var addr in GetAddresses()) - { - if (address.Equals(addr)) - { - return true; - } - } - } - - return false; - } - - /// - public override bool Equals(IPObject? other) - { - if (other is IPHost otherObj) - { - // Do we have the name Hostname? - if (string.Equals(otherObj.HostName, HostName, StringComparison.OrdinalIgnoreCase)) - { - return true; - } - - if (!ResolveHost() || !otherObj.ResolveHost()) - { - return false; - } - - // Do any of our IP addresses match? - foreach (IPAddress addr in _addresses) - { - foreach (IPAddress otherAddress in otherObj._addresses) - { - if (addr.Equals(otherAddress)) - { - return true; - } - } - } - } - - return false; - } - - /// - public override bool IsIP6() - { - // Returns true if interfaces are only IP6. - if (ResolveHost()) - { - foreach (IPAddress i in _addresses) - { - if (i.AddressFamily != AddressFamily.InterNetworkV6) - { - return false; - } - } - - return true; - } - - return false; - } - - /// - public override string ToString() - { - // StringBuilder not optimum here. - string output = string.Empty; - if (_addresses.Length > 0) - { - bool moreThanOne = _addresses.Length > 1; - if (moreThanOne) - { - output = "["; - } - - foreach (var i in _addresses) - { - if (Address.Equals(IPAddress.None) && Address.AddressFamily == AddressFamily.Unspecified) - { - output += HostName + ","; - } - else if (i.Equals(IPAddress.Any)) - { - output += "Any IP4 Address,"; - } - else if (Address.Equals(IPAddress.IPv6Any)) - { - output += "Any IP6 Address,"; - } - else if (i.Equals(IPAddress.Broadcast)) - { - output += "Any Address,"; - } - else if (i.AddressFamily == AddressFamily.InterNetwork) - { - output += $"{i}/32,"; - } - else - { - output += $"{i}/128,"; - } - } - - output = output[..^1]; - - if (moreThanOne) - { - output += "]"; - } - } - else - { - output = HostName; - } - - return output; - } - - /// - public override void Remove(AddressFamily family) - { - if (ResolveHost()) - { - _addresses = _addresses.Where(p => p.AddressFamily != family).ToArray(); - } - } - - /// - public override bool Contains(IPObject address) - { - // An IPHost cannot contain another IPObject, it can only be equal. - return Equals(address); - } - - /// - protected override IPObject CalculateNetworkAddress() - { - var (address, prefixLength) = NetworkAddressOf(this[0], PrefixLength); - return new IPNetAddress(address, prefixLength); - } - - /// - /// Attempt to resolve the ip address of a host. - /// - /// true if any addresses have been resolved, otherwise false. - private bool ResolveHost() - { - // When was the last time we resolved? - _lastResolved ??= DateTime.UtcNow; - - // If we haven't resolved before, or our timer has run out... - if ((_addresses.Length == 0 && !Resolved) || (DateTime.UtcNow > _lastResolved.Value.AddMinutes(Timeout))) - { - _lastResolved = DateTime.UtcNow; - ResolveHostInternal(); - Resolved = true; - } - - return _addresses.Length > 0; - } - - /// - /// Task that looks up a Host name and returns its IP addresses. - /// - private void ResolveHostInternal() - { - var hostName = HostName; - if (string.IsNullOrEmpty(hostName)) - { - return; - } - - // Resolves the host name - so save a DNS lookup. - if (string.Equals(hostName, "localhost", StringComparison.OrdinalIgnoreCase)) - { - _addresses = new IPAddress[] { IPAddress.Loopback, IPAddress.IPv6Loopback }; - return; - } - - if (Uri.CheckHostName(hostName) == UriHostNameType.Dns) - { - try - { - _addresses = Dns.GetHostEntry(hostName).AddressList; - } - catch (SocketException ex) - { - // Log and then ignore socket errors, as the result value will just be an empty array. - Debug.WriteLine("GetHostAddresses failed with {Message}.", ex.Message); - } - } - } - } -} diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs deleted file mode 100644 index f1428d4bef..0000000000 --- a/MediaBrowser.Common/Net/IPNetAddress.cs +++ /dev/null @@ -1,276 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; - -namespace MediaBrowser.Common.Net -{ - /// - /// An object that holds and IP address and subnet mask. - /// - public class IPNetAddress : IPObject - { - /// - /// Represents an IPNetAddress that has no value. - /// - public static readonly IPNetAddress None = new IPNetAddress(IPAddress.None); - - /// - /// IPv4 multicast address. - /// - public static readonly IPAddress SSDPMulticastIPv4 = IPAddress.Parse("239.255.255.250"); - - /// - /// IPv6 local link multicast address. - /// - public static readonly IPAddress SSDPMulticastIPv6LinkLocal = IPAddress.Parse("ff02::C"); - - /// - /// IPv6 site local multicast address. - /// - public static readonly IPAddress SSDPMulticastIPv6SiteLocal = IPAddress.Parse("ff05::C"); - - /// - /// IP4Loopback address host. - /// - public static readonly IPNetAddress IP4Loopback = IPNetAddress.Parse("127.0.0.1/8"); - - /// - /// IP6Loopback address host. - /// - public static readonly IPNetAddress IP6Loopback = new IPNetAddress(IPAddress.IPv6Loopback); - - /// - /// Object's IP address. - /// - private IPAddress _address; - - /// - /// Initializes a new instance of the class. - /// - /// Address to assign. - public IPNetAddress(IPAddress address) - { - _address = address ?? throw new ArgumentNullException(nameof(address)); - PrefixLength = (byte)(address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128); - } - - /// - /// Initializes a new instance of the class. - /// - /// IP Address. - /// Mask as a CIDR. - public IPNetAddress(IPAddress address, byte prefixLength) - { - if (address?.IsIPv4MappedToIPv6 ?? throw new ArgumentNullException(nameof(address))) - { - _address = address.MapToIPv4(); - } - else - { - _address = address; - } - - PrefixLength = prefixLength; - } - - /// - /// Gets or sets the object's IP address. - /// - public override IPAddress Address - { - get - { - return _address; - } - - set - { - _address = value ?? IPAddress.None; - } - } - - /// - public override byte PrefixLength { get; set; } - - /// - /// Try to parse the address and subnet strings into an IPNetAddress object. - /// - /// IP address to parse. Can be CIDR or X.X.X.X notation. - /// Resultant object. - /// True if the values parsed successfully. False if not, resulting in the IP being null. - public static bool TryParse(string addr, out IPNetAddress ip) - { - if (!string.IsNullOrEmpty(addr)) - { - addr = addr.Trim(); - - // Try to parse it as is. - if (IPAddress.TryParse(addr, out IPAddress? res)) - { - ip = new IPNetAddress(res); - return true; - } - - // Is it a network? - string[] tokens = addr.Split('/'); - - if (tokens.Length == 2) - { - tokens[0] = tokens[0].TrimEnd(); - tokens[1] = tokens[1].TrimStart(); - - if (IPAddress.TryParse(tokens[0], out res)) - { - // Is the subnet part a cidr? - if (byte.TryParse(tokens[1], out byte cidr)) - { - ip = new IPNetAddress(res, cidr); - return true; - } - - // Is the subnet in x.y.a.b form? - if (IPAddress.TryParse(tokens[1], out IPAddress? mask)) - { - ip = new IPNetAddress(res, MaskToCidr(mask)); - return true; - } - } - } - } - - ip = None; - return false; - } - - /// - /// Parses the string provided, throwing an exception if it is badly formed. - /// - /// String to parse. - /// IPNetAddress object. - public static IPNetAddress Parse(string addr) - { - if (TryParse(addr, out IPNetAddress o)) - { - return o; - } - - throw new ArgumentException("Unable to recognise object :" + addr); - } - - /// - public override bool Contains(IPAddress address) - { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } - - if (address.IsIPv4MappedToIPv6) - { - address = address.MapToIPv4(); - } - - var (altAddress, altPrefix) = NetworkAddressOf(address, PrefixLength); - return NetworkAddress.Address.Equals(altAddress) && NetworkAddress.PrefixLength >= altPrefix; - } - - /// - public override bool Contains(IPObject address) - { - if (address is IPHost addressObj && addressObj.HasAddress) - { - foreach (IPAddress addr in addressObj.GetAddresses()) - { - if (Contains(addr)) - { - return true; - } - } - } - else if (address is IPNetAddress netaddrObj) - { - // Have the same network address, but different subnets? - if (NetworkAddress.Address.Equals(netaddrObj.NetworkAddress.Address)) - { - return NetworkAddress.PrefixLength <= netaddrObj.PrefixLength; - } - - var altAddress = NetworkAddressOf(netaddrObj.Address, PrefixLength).Address; - return NetworkAddress.Address.Equals(altAddress); - } - - return false; - } - - /// - public override bool Equals(IPObject? other) - { - if (other is IPNetAddress otherObj && !Address.Equals(IPAddress.None) && !otherObj.Address.Equals(IPAddress.None)) - { - return Address.Equals(otherObj.Address) && - PrefixLength == otherObj.PrefixLength; - } - - return false; - } - - /// - public override bool Equals(IPAddress ip) - { - if (ip != null && !ip.Equals(IPAddress.None) && !Address.Equals(IPAddress.None)) - { - return ip.Equals(Address); - } - - return false; - } - - /// - public override string ToString() - { - return ToString(false); - } - - /// - /// Returns a textual representation of this object. - /// - /// Set to true, if the subnet is to be excluded as part of the address. - /// String representation of this object. - public string ToString(bool shortVersion) - { - if (!Address.Equals(IPAddress.None)) - { - if (Address.Equals(IPAddress.Any)) - { - return "Any IP4 Address"; - } - - if (Address.Equals(IPAddress.IPv6Any)) - { - return "Any IP6 Address"; - } - - if (Address.Equals(IPAddress.Broadcast)) - { - return "Any Address"; - } - - if (shortVersion) - { - return Address.ToString(); - } - - return $"{Address}/{PrefixLength}"; - } - - return string.Empty; - } - - /// - protected override IPObject CalculateNetworkAddress() - { - var (address, prefixLength) = NetworkAddressOf(_address, PrefixLength); - return new IPNetAddress(address, prefixLength); - } - } -} diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs deleted file mode 100644 index 3a5187bc3d..0000000000 --- a/MediaBrowser.Common/Net/IPObject.cs +++ /dev/null @@ -1,370 +0,0 @@ -using System; -using System.Net; -using System.Net.Sockets; - -namespace MediaBrowser.Common.Net -{ - /// - /// Base network object class. - /// - public abstract class IPObject : IEquatable - { - /// - /// The network address of this object. - /// - private IPObject? _networkAddress; - - /// - /// Gets or sets a user defined value that is associated with this object. - /// - public int Tag { get; set; } - - /// - /// Gets or sets the object's IP address. - /// - public abstract IPAddress Address { get; set; } - - /// - /// Gets the object's network address. - /// - public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress(); - - /// - /// Gets or sets the object's IP address. - /// - public abstract byte PrefixLength { get; set; } - - /// - /// Gets the AddressFamily of this object. - /// - public AddressFamily AddressFamily - { - get - { - // Keep terms separate as Address performs other functions in inherited objects. - IPAddress address = Address; - return address.Equals(IPAddress.None) ? AddressFamily.Unspecified : address.AddressFamily; - } - } - - /// - /// Returns the network address of an object. - /// - /// IP Address to convert. - /// Subnet prefix. - /// IPAddress. - public static (IPAddress Address, byte PrefixLength) NetworkAddressOf(IPAddress address, byte prefixLength) - { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } - - if (address.IsIPv4MappedToIPv6) - { - address = address.MapToIPv4(); - } - - if (IPAddress.IsLoopback(address)) - { - return (address, prefixLength); - } - - // An ip address is just a list of bytes, each one representing a segment on the network. - // This separates the IP address into octets and calculates how many octets will need to be altered or set to zero dependant upon the - // prefix length value. eg. /16 on a 4 octet ip4 address (192.168.2.240) will result in the 2 and the 240 being zeroed out. - // Where there is not an exact boundary (eg /23), mod is used to calculate how many bits of this value are to be kept. - - // GetAddressBytes - Span addressBytes = stackalloc byte[address.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; - address.TryWriteBytes(addressBytes, out _); - - int div = prefixLength / 8; - int mod = prefixLength % 8; - if (mod != 0) - { - // Prefix length is counted right to left, so subtract 8 so we know how many bits to clear. - mod = 8 - mod; - - // Shift out the bits from the octet that we don't want, by moving right then back left. - addressBytes[div] = (byte)((int)addressBytes[div] >> mod << mod); - // Move on the next byte. - div++; - } - - // Blank out the remaining octets from mod + 1 to the end of the byte array. (192.168.2.240/16 becomes 192.168.0.0) - for (int octet = div; octet < addressBytes.Length; octet++) - { - addressBytes[octet] = 0; - } - - // Return the network address for the prefix. - return (new IPAddress(addressBytes), prefixLength); - } - - /// - /// Tests to see if the ip address is an IP6 address. - /// - /// Value to test. - /// True if it is. - public static bool IsIP6(IPAddress address) - { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } - - if (address.IsIPv4MappedToIPv6) - { - address = address.MapToIPv4(); - } - - return !address.Equals(IPAddress.None) && (address.AddressFamily == AddressFamily.InterNetworkV6); - } - - /// - /// Tests to see if the address in the private address range. - /// - /// Object to test. - /// True if it contains a private address. - public static bool IsPrivateAddressRange(IPAddress address) - { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } - - if (!address.Equals(IPAddress.None)) - { - if (address.IsIPv4MappedToIPv6) - { - address = address.MapToIPv4(); - } - - if (address.AddressFamily == AddressFamily.InterNetwork) - { - // GetAddressBytes - Span octet = stackalloc byte[4]; - address.TryWriteBytes(octet, out _); - - return (octet[0] == 10) - || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918 - || (octet[0] == 192 && octet[1] == 168) // RFC1918 - || (octet[0] == 127); // RFC1122 - } - else - { - // GetAddressBytes - Span octet = stackalloc byte[16]; - address.TryWriteBytes(octet, out _); - - uint word = (uint)(octet[0] << 8) + octet[1]; - - return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link. - || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address. - } - } - - return false; - } - - /// - /// Returns true if the IPAddress contains an IP6 Local link address. - /// - /// IPAddress object to check. - /// True if it is a local link address. - /// - /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress - /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. - /// - public static bool IsIPv6LinkLocal(IPAddress address) - { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } - - if (address.IsIPv4MappedToIPv6) - { - address = address.MapToIPv4(); - } - - if (address.AddressFamily != AddressFamily.InterNetworkV6) - { - return false; - } - - // GetAddressBytes - Span octet = stackalloc byte[16]; - address.TryWriteBytes(octet, out _); - uint word = (uint)(octet[0] << 8) + octet[1]; - - return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link. - } - - /// - /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. - /// - /// Subnet mask in CIDR notation. - /// IPv4 or IPv6 family. - /// String value of the subnet mask in dotted decimal notation. - public static IPAddress CidrToMask(byte cidr, AddressFamily family) - { - uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr); - addr = ((addr & 0xff000000) >> 24) - | ((addr & 0x00ff0000) >> 8) - | ((addr & 0x0000ff00) << 8) - | ((addr & 0x000000ff) << 24); - return new IPAddress(addr); - } - - /// - /// Convert a mask to a CIDR. IPv4 only. - /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. - /// - /// Subnet mask. - /// Byte CIDR representing the mask. - public static byte MaskToCidr(IPAddress mask) - { - if (mask == null) - { - throw new ArgumentNullException(nameof(mask)); - } - - byte cidrnet = 0; - if (!mask.Equals(IPAddress.Any)) - { - // GetAddressBytes - Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; - mask.TryWriteBytes(bytes, out _); - - var zeroed = false; - for (var i = 0; i < bytes.Length; i++) - { - for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1) - { - if (zeroed) - { - // Invalid netmask. - return (byte)~cidrnet; - } - - if ((v & 0x80) == 0) - { - zeroed = true; - } - else - { - cidrnet++; - } - } - } - } - - return cidrnet; - } - - /// - /// Tests to see if this object is a Loopback address. - /// - /// True if it is. - public virtual bool IsLoopback() - { - return IPAddress.IsLoopback(Address); - } - - /// - /// Removes all addresses of a specific type from this object. - /// - /// Type of address to remove. - public virtual void Remove(AddressFamily family) - { - // This method only performs a function in the IPHost implementation of IPObject. - } - - /// - /// Tests to see if this object is an IPv6 address. - /// - /// True if it is. - public virtual bool IsIP6() - { - return IsIP6(Address); - } - - /// - /// Returns true if this IP address is in the RFC private address range. - /// - /// True this object has a private address. - public virtual bool IsPrivateAddressRange() - { - return IsPrivateAddressRange(Address); - } - - /// - /// Compares this to the object passed as a parameter. - /// - /// Object to compare to. - /// Equality result. - public virtual bool Equals(IPAddress ip) - { - if (ip != null) - { - if (ip.IsIPv4MappedToIPv6) - { - ip = ip.MapToIPv4(); - } - - return !Address.Equals(IPAddress.None) && Address.Equals(ip); - } - - return false; - } - - /// - /// Compares this to the object passed as a parameter. - /// - /// Object to compare to. - /// Equality result. - public virtual bool Equals(IPObject? other) - { - if (other != null) - { - return !Address.Equals(IPAddress.None) && Address.Equals(other.Address); - } - - return false; - } - - /// - /// Compares the address in this object and the address in the object passed as a parameter. - /// - /// Object's IP address to compare to. - /// Comparison result. - public abstract bool Contains(IPObject address); - - /// - /// Compares the address in this object and the address in the object passed as a parameter. - /// - /// Object's IP address to compare to. - /// Comparison result. - public abstract bool Contains(IPAddress address); - - /// - public override int GetHashCode() - { - return Address.GetHashCode(); - } - - /// - public override bool Equals(object? obj) - { - return Equals(obj as IPObject); - } - - /// - /// Calculates the network address of this object. - /// - /// Returns the network address of this object. - protected abstract IPObject CalculateNetworkAddress(); - } -} diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index 264bfacb49..55ec322f43 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -1,6 +1,9 @@ using System; -using System.Collections.ObjectModel; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Net; +using System.Net.Sockets; +using System.Text.RegularExpressions; namespace MediaBrowser.Common.Net { @@ -10,251 +13,209 @@ namespace MediaBrowser.Common.Net public static class NetworkExtensions { /// - /// Add an address to the collection. + /// Returns true if the IPAddress contains an IP6 Local link address. /// - /// The . - /// Item to add. - public static void AddItem(this Collection source, IPAddress ip) + /// IPAddress object to check. + /// True if it is a local link address. + /// + /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress + /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. + /// + public static bool IsIPv6LinkLocal(IPAddress address) { - if (!source.ContainsAddress(ip)) + if (address == null) { - source.Add(new IPNetAddress(ip, 32)); + throw new ArgumentNullException(nameof(address)); } - } - /// - /// Adds a network to the collection. - /// - /// The . - /// Item to add. - /// If true the values are treated as subnets. - /// If false items are addresses. - public static void AddItem(this Collection source, IPObject item, bool itemsAreNetworks = true) - { - if (!source.ContainsAddress(item) || !itemsAreNetworks) + if (address.IsIPv4MappedToIPv6) { - source.Add(item); + address = address.MapToIPv4(); } - } - /// - /// Converts this object to a string. - /// - /// The . - /// Returns a string representation of this object. - public static string AsString(this Collection source) - { - return $"[{string.Join(',', source)}]"; - } - - /// - /// Returns true if the collection contains an item with the ip address, - /// or the ip address falls within any of the collection's network ranges. - /// - /// The . - /// The item to look for. - /// True if the collection contains the item. - public static bool ContainsAddress(this Collection source, IPAddress item) - { - if (source.Count == 0) + if (address.AddressFamily != AddressFamily.InterNetworkV6) { return false; } - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + // GetAddressBytes + Span octet = stackalloc byte[16]; + address.TryWriteBytes(octet, out _); + uint word = (uint)(octet[0] << 8) + octet[1]; - if (item.IsIPv4MappedToIPv6) - { - item = item.MapToIPv4(); - } - - foreach (var i in source) - { - if (i.Contains(item)) - { - return true; - } - } - - return false; + return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link. } /// - /// Returns true if the collection contains an item with the ip address, - /// or the ip address falls within any of the collection's network ranges. + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. /// - /// The . - /// The item to look for. - /// True if the collection contains the item. - public static bool ContainsAddress(this Collection source, IPObject item) + /// Subnet mask in CIDR notation. + /// IPv4 or IPv6 family. + /// String value of the subnet mask in dotted decimal notation. + public static IPAddress CidrToMask(byte cidr, AddressFamily family) { - if (source.Count == 0) - { - return false; - } - - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } - - foreach (var i in source) - { - if (i.Contains(item)) - { - return true; - } - } - - return false; + uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr); + addr = ((addr & 0xff000000) >> 24) + | ((addr & 0x00ff0000) >> 8) + | ((addr & 0x0000ff00) << 8) + | ((addr & 0x000000ff) << 24); + return new IPAddress(addr); } /// - /// Compares two Collection{IPObject} objects. The order is ignored. + /// Convert a subnet mask to a CIDR. IPv4 only. + /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. /// - /// The . - /// Item to compare to. - /// True if both are equal. - public static bool Compare(this Collection source, Collection dest) + /// Subnet mask. + /// Byte CIDR representing the mask. + public static byte MaskToCidr(IPAddress mask) { - if (dest == null || source.Count != dest.Count) + if (mask == null) { - return false; + throw new ArgumentNullException(nameof(mask)); } - foreach (var sourceItem in source) + byte cidrnet = 0; + if (!mask.Equals(IPAddress.Any)) { - bool found = false; - foreach (var destItem in dest) + // GetAddressBytes + Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16]; + mask.TryWriteBytes(bytes, out _); + + var zeroed = false; + for (var i = 0; i < bytes.Length; i++) { - if (sourceItem.Equals(destItem)) + for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1) { - found = true; - break; - } - } - - if (!found) - { - return false; - } - } - - return true; - } - - /// - /// Returns a collection containing the subnets of this collection given. - /// - /// The . - /// Collection{IPObject} object containing the subnets. - public static Collection AsNetworks(this Collection source) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - Collection res = new Collection(); - - foreach (IPObject i in source) - { - if (i is IPNetAddress nw) - { - // Add the subnet calculated from the interface address/mask. - var na = nw.NetworkAddress; - na.Tag = i.Tag; - res.AddItem(na); - } - else if (i is IPHost ipHost) - { - // Flatten out IPHost and add all its ip addresses. - foreach (var addr in ipHost.GetAddresses()) - { - IPNetAddress host = new IPNetAddress(addr) + if (zeroed) { - Tag = i.Tag - }; + // Invalid netmask. + return (byte)~cidrnet; + } - res.AddItem(host); + if ((v & 0x80) == 0) + { + zeroed = true; + } + else + { + cidrnet++; + } } } } - return res; + return cidrnet; } /// - /// Excludes all the items from this list that are found in excludeList. + /// Converts an IPAddress into a string. + /// Ipv6 addresses are returned in [ ], with their scope removed. /// - /// The . - /// Items to exclude. - /// Collection is a network collection. - /// A new collection, with the items excluded. - public static Collection Exclude(this Collection source, Collection excludeList, bool isNetwork) + /// Address to convert. + /// URI safe conversion of the address. + public static string FormatIpString(IPAddress? address) { - if (source.Count == 0 || excludeList == null) + if (address == null) { - return new Collection(source); + return string.Empty; } - Collection results = new Collection(); - - bool found; - foreach (var outer in source) + var str = address.ToString(); + if (address.AddressFamily == AddressFamily.InterNetworkV6) { - found = false; - - foreach (var inner in excludeList) + int i = str.IndexOf('%', StringComparison.Ordinal); + if (i != -1) { - if (outer.Equals(inner)) + str = str.Substring(0, i); + } + + return $"[{str}]"; + } + + return str; + } + + /// + /// Attempts to parse a host string. + /// + /// Host name to parse. + /// Object representing the string, if it has successfully been parsed. + /// true if IPv4 is enabled. + /// true if IPv6 is enabled. + /// true if the parsing is successful, false if not. + public static bool TryParseHost(string host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIpv4Enabled = true, bool isIpv6Enabled = false) + { + if (string.IsNullOrWhiteSpace(host)) + { + addresses = Array.Empty(); + return false; + } + + host = host.Trim(); + + // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. + if (host[0] == '[') + { + int i = host.IndexOf(']', StringComparison.Ordinal); + if (i != -1) + { + return TryParseHost(host.Remove(i)[1..], out addresses); + } + + addresses = Array.Empty(); + return false; + } + + var hosts = host.Split(':'); + + if (hosts.Length <= 2) + { + // Use regular expression as CheckHostName isn't RFC5892 compliant. + // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation + string pattern = @"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$"; + + // Is hostname or hostname:port + if (Regex.IsMatch(hosts[0], pattern)) + { + try { - found = true; - break; + addresses = Dns.GetHostAddresses(hosts[0]); + return true; + } + catch (SocketException) + { + // Log and then ignore socket errors, as the result value will just be an empty array. + Console.WriteLine("GetHostAddresses failed."); } } - if (!found) + // Is an IP4 or IP4:port + host = hosts[0].Split('/')[0]; + + if (IPAddress.TryParse(host, out var address)) { - results.AddItem(outer, isNetwork); + if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIpv4Enabled && isIpv6Enabled)) || + ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIpv4Enabled && !isIpv6Enabled))) + { + addresses = Array.Empty(); + return false; + } + + addresses = new[] { address }; + + // Host name is an ip4 address, so fake resolve. + return true; } } - - return results; - } - - /// - /// Returns all items that co-exist in this object and target. - /// - /// The . - /// Collection to compare with. - /// A collection containing all the matches. - public static Collection ThatAreContainedInNetworks(this Collection source, Collection target) - { - if (source.Count == 0) + else if (hosts.Length <= 9 && IPAddress.TryParse(host.Split('/')[0], out var address)) // 8 octets + port { - return new Collection(); + addresses = new[] { address }; + return true; } - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - Collection nc = new Collection(); - - foreach (IPObject i in source) - { - if (target.ContainsAddress(i)) - { - nc.AddItem(i); - } - } - - return nc; + addresses = Array.Empty(); + return false; } } } diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs index 11afdc4aed..45ac5c3a85 100644 --- a/MediaBrowser.Controller/IServerApplicationHost.cs +++ b/MediaBrowser.Controller/IServerApplicationHost.cs @@ -4,7 +4,6 @@ using System.Net; using MediaBrowser.Common; -using MediaBrowser.Common.Net; using MediaBrowser.Model.System; using Microsoft.AspNetCore.Http; @@ -75,10 +74,10 @@ namespace MediaBrowser.Controller /// /// Gets an URL that can be used to access the API over LAN. /// - /// An optional hostname to use. + /// An optional IP address to use. /// A value indicating whether to allow HTTPS. /// The API URL. - string GetApiUrlForLocalAccess(IPObject hostname = null, bool allowHttps = true); + string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true); /// /// Gets a local (LAN) URL that can be used to access the API. diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs index a7767b3c04..37c4128ba4 100644 --- a/RSSDP/SsdpDevicePublisher.cs +++ b/RSSDP/SsdpDevicePublisher.cs @@ -7,6 +7,7 @@ using System.Net; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Common.Net; +using Microsoft.AspNetCore.HttpOverrides; namespace Rssdp.Infrastructure { @@ -297,9 +298,9 @@ namespace Rssdp.Infrastructure foreach (var device in deviceList) { var root = device.ToRootDevice(); - var source = new IPNetAddress(root.Address, root.PrefixLength); - var destination = new IPNetAddress(remoteEndPoint.Address, root.PrefixLength); - if (!_sendOnlyMatchedHost || source.NetworkAddress.Equals(destination.NetworkAddress)) + var source = new IPData(root.Address, new IPNetwork(root.Address, root.PrefixLength), root.FriendlyName); + var destination = new IPData(remoteEndPoint.Address, new IPNetwork(root.Address, root.PrefixLength)); + if (!_sendOnlyMatchedHost || source.Address.Equals(destination.Address)) { SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken); } diff --git a/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs b/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs deleted file mode 100644 index aa2dbc57a2..0000000000 --- a/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs +++ /dev/null @@ -1,49 +0,0 @@ -using FsCheck; -using FsCheck.Xunit; -using MediaBrowser.Common.Net; -using Xunit; - -namespace Jellyfin.Networking.Tests -{ - public static class IPNetAddressTests - { - /// - /// Checks IP address formats. - /// - /// IP Address. - [Theory] - [InlineData("127.0.0.1")] - [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")] - [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")] - [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]")] - [InlineData("fe80::7add:12ff:febb:c67b%16")] - [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")] - [InlineData("fe80::7add:12ff:febb:c67b%16:123")] - [InlineData("[fe80::7add:12ff:febb:c67b%16]")] - [InlineData("192.168.1.2/255.255.255.0")] - [InlineData("192.168.1.2/24")] - public static void TryParse_ValidIPStrings_True(string address) - => Assert.True(IPNetAddress.TryParse(address, out _)); - - [Property] - public static Property TryParse_IPv4Address_True(IPv4Address address) - => IPNetAddress.TryParse(address.Item.ToString(), out _).ToProperty(); - - [Property] - public static Property TryParse_IPv6Address_True(IPv6Address address) - => IPNetAddress.TryParse(address.Item.ToString(), out _).ToProperty(); - - /// - /// All should be invalid address strings. - /// - /// Invalid address strings. - [Theory] - [InlineData("256.128.0.0.0.1")] - [InlineData("127.0.0.1#")] - [InlineData("localhost!")] - [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")] - [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")] - public static void TryParse_InvalidAddressString_False(string address) - => Assert.False(IPNetAddress.TryParse(address, out _)); - } -} diff --git a/tests/Jellyfin.Networking.Tests/IPHostTests.cs b/tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs similarity index 80% rename from tests/Jellyfin.Networking.Tests/IPHostTests.cs rename to tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs index ec3a1300c8..c81fdefe95 100644 --- a/tests/Jellyfin.Networking.Tests/IPHostTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs @@ -5,7 +5,7 @@ using Xunit; namespace Jellyfin.Networking.Tests { - public static class IPHostTests + public static class NetworkExtensionsTests { /// /// Checks IP address formats. @@ -27,15 +27,15 @@ namespace Jellyfin.Networking.Tests [InlineData("192.168.1.2/255.255.255.0")] [InlineData("192.168.1.2/24")] public static void TryParse_ValidHostStrings_True(string address) - => Assert.True(IPHost.TryParse(address, out _)); + => Assert.True(NetworkExtensions.TryParseHost(address, out _, true, true)); [Property] public static Property TryParse_IPv4Address_True(IPv4Address address) - => IPHost.TryParse(address.Item.ToString(), out _).ToProperty(); + => NetworkExtensions.TryParseHost(address.Item.ToString(), out _, true, true).ToProperty(); [Property] public static Property TryParse_IPv6Address_True(IPv6Address address) - => IPHost.TryParse(address.Item.ToString(), out _).ToProperty(); + => NetworkExtensions.TryParseHost(address.Item.ToString(), out _, true, true).ToProperty(); /// /// All should be invalid address strings. @@ -48,6 +48,6 @@ namespace Jellyfin.Networking.Tests [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")] [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")] public static void TryParse_InvalidAddressString_False(string address) - => Assert.False(IPHost.TryParse(address, out _)); + => Assert.False(NetworkExtensions.TryParseHost(address, out _, true, true)); } } diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs index 6b93974373..ce638c9136 100644 --- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs +++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs @@ -1,10 +1,13 @@ using System; using System.Collections.ObjectModel; +using System.Globalization; +using System.Linq; using System.Net; using Jellyfin.Networking.Configuration; using Jellyfin.Networking.Manager; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; +using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; @@ -46,6 +49,8 @@ namespace Jellyfin.Networking.Tests { EnableIPV6 = true, EnableIPV4 = true, + IgnoreVirtualInterfaces = true, + VirtualInterfaceNames = "veth", LocalNetworkSubnets = lan?.Split(';') ?? throw new ArgumentNullException(nameof(lan)) }; @@ -53,135 +58,7 @@ namespace Jellyfin.Networking.Tests using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); NetworkManager.MockNetworkSettings = string.Empty; - Assert.Equal(nm.GetInternalBindAddresses().AsString(), value); - } - - /// - /// Test collection parsing. - /// - /// Collection to parse. - /// Included addresses from the collection. - /// Included IP4 addresses from the collection. - /// Excluded addresses from the collection. - /// Excluded IP4 addresses from the collection. - /// Network addresses of the collection. - [Theory] - [InlineData( - "127.0.0.1#", - "[]", - "[]", - "[]", - "[]", - "[]")] - [InlineData( - "!127.0.0.1", - "[]", - "[]", - "[127.0.0.1/32]", - "[127.0.0.1/32]", - "[]")] - [InlineData( - "", - "[]", - "[]", - "[]", - "[]", - "[]")] - [InlineData( - "192.158.1.2/16, localhost, fd23:184f:2029:0:3139:7386:67d7:d517, !10.10.10.10", - "[192.158.1.2/16,[127.0.0.1/32,::1/128],fd23:184f:2029:0:3139:7386:67d7:d517/128]", - "[192.158.1.2/16,127.0.0.1/32]", - "[10.10.10.10/32]", - "[10.10.10.10/32]", - "[192.158.0.0/16,127.0.0.1/32,::1/128,fd23:184f:2029:0:3139:7386:67d7:d517/128]")] - [InlineData( - "192.158.1.2/255.255.0.0,192.169.1.2/8", - "[192.158.1.2/16,192.169.1.2/8]", - "[192.158.1.2/16,192.169.1.2/8]", - "[]", - "[]", - "[192.158.0.0/16,192.0.0.0/8]")] - public void TestCollections(string settings, string result1, string result2, string result3, string result4, string result5) - { - if (settings == null) - { - throw new ArgumentNullException(nameof(settings)); - } - - var conf = new NetworkConfiguration() - { - EnableIPV6 = true, - EnableIPV4 = true, - }; - - using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - - // Test included. - Collection nc = nm.CreateIPCollection(settings.Split(','), false); - Assert.Equal(nc.AsString(), result1); - - // Test excluded. - nc = nm.CreateIPCollection(settings.Split(','), true); - Assert.Equal(nc.AsString(), result3); - - conf.EnableIPV6 = false; - nm.UpdateSettings(conf); - - // Test IP4 included. - nc = nm.CreateIPCollection(settings.Split(','), false); - Assert.Equal(nc.AsString(), result2); - - // Test IP4 excluded. - nc = nm.CreateIPCollection(settings.Split(','), true); - Assert.Equal(nc.AsString(), result4); - - conf.EnableIPV6 = true; - nm.UpdateSettings(conf); - - // Test network addresses of collection. - nc = nm.CreateIPCollection(settings.Split(','), false); - nc = nc.AsNetworks(); - Assert.Equal(nc.AsString(), result5); - } - - /// - /// Union two collections. - /// - /// Source. - /// Destination. - /// Result. - [Theory] - [InlineData("127.0.0.1", "fd23:184f:2029:0:3139:7386:67d7:d517/64,fd23:184f:2029:0:c0f0:8a8a:7605:fffa/128,fe80::3139:7386:67d7:d517%16/64,192.168.1.208/24,::1/128,127.0.0.1/8", "[127.0.0.1/32]")] - [InlineData("127.0.0.1", "127.0.0.1/8", "[127.0.0.1/32]")] - public void UnionCheck(string settings, string compare, string result) - { - if (settings == null) - { - throw new ArgumentNullException(nameof(settings)); - } - - if (compare == null) - { - throw new ArgumentNullException(nameof(compare)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } - - var conf = new NetworkConfiguration() - { - EnableIPV6 = true, - EnableIPV4 = true, - }; - - using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - - Collection nc1 = nm.CreateIPCollection(settings.Split(','), false); - Collection nc2 = nm.CreateIPCollection(compare.Split(','), false); - - Assert.Equal(nc1.ThatAreContainedInNetworks(nc2).AsString(), result); + Assert.Equal(value, "[" + String.Join(",", nm.GetInternalBindAddresses().Select(x => x.Address + "/" + x.Subnet.PrefixLength)) + "]"); } [Theory] @@ -194,8 +71,11 @@ namespace Jellyfin.Networking.Tests [InlineData("127.0.0.1/8", "127.0.0.1")] public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) { - var ipAddressObj = IPNetAddress.Parse(netMask); - Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress))); + var split = netMask.Split("/"); + var mask = int.Parse(split[1], CultureInfo.InvariantCulture); + var ipa = IPAddress.Parse(split[0]); + var ipn = new IPNetwork(ipa, mask); + Assert.True(ipn.Contains(IPAddress.Parse(ipAddress))); } [Theory] @@ -207,8 +87,11 @@ namespace Jellyfin.Networking.Tests [InlineData("10.128.240.50/30", "10.127.240.51")] public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) { - var ipAddressObj = IPNetAddress.Parse(netMask); - Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress))); + var split = netMask.Split("/"); + var mask = int.Parse(split[1], CultureInfo.InvariantCulture); + var ipa = IPAddress.Parse(split[0]); + var ipn = new IPNetwork(ipa, mask); + Assert.False(ipn.Contains(IPAddress.Parse(ipAddress))); } [Theory] @@ -219,8 +102,11 @@ namespace Jellyfin.Networking.Tests [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")] public void IpV6SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress) { - var ipAddressObj = IPNetAddress.Parse(netMask); - Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress))); + var split = netMask.Split("/"); + var mask = int.Parse(split[1], CultureInfo.InvariantCulture); + var ipa = IPAddress.Parse(split[0]); + var ipn = new IPNetwork(ipa, mask); + Assert.True(ipn.Contains(IPAddress.Parse(ipAddress))); } [Theory] @@ -231,86 +117,18 @@ namespace Jellyfin.Networking.Tests [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0001")] public void IpV6SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress) { - var ipAddressObj = IPNetAddress.Parse(netMask); - Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress))); + var split = netMask.Split("/"); + var mask = int.Parse(split[1], CultureInfo.InvariantCulture); + var ipa = IPAddress.Parse(split[0]); + var ipn = new IPNetwork(ipa, mask); + Assert.False(ipn.Contains(IPAddress.Parse(ipAddress))); } [Theory] - [InlineData("10.0.0.0/255.0.0.0", "10.10.10.1/32")] - [InlineData("10.0.0.0/8", "10.10.10.1/32")] - [InlineData("10.0.0.0/255.0.0.0", "10.10.10.1")] - - [InlineData("10.10.0.0/255.255.0.0", "10.10.10.1/32")] - [InlineData("10.10.0.0/16", "10.10.10.1/32")] - [InlineData("10.10.0.0/255.255.0.0", "10.10.10.1")] - - [InlineData("10.10.10.0/255.255.255.0", "10.10.10.1/32")] - [InlineData("10.10.10.0/24", "10.10.10.1/32")] - [InlineData("10.10.10.0/255.255.255.0", "10.10.10.1")] - - public void TestSubnetContains(string network, string ip) - { - Assert.True(IPNetAddress.TryParse(network, out var networkObj)); - Assert.True(IPNetAddress.TryParse(ip, out var ipObj)); - Assert.True(networkObj.Contains(ipObj)); - } - - [Theory] - [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24", "172.168.1.2/24")] - [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24, 10.10.10.1", "172.168.1.2/24,10.10.10.1/24")] - [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/255.255.255.0, 10.10.10.1", "192.168.1.2/24,10.10.10.1/24")] - [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/24, 100.10.10.1", "192.168.1.2/24")] - [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "194.168.1.2/24, 100.10.10.1", "")] - - public void TestCollectionEquality(string source, string dest, string result) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - if (dest == null) - { - throw new ArgumentNullException(nameof(dest)); - } - - if (result == null) - { - throw new ArgumentNullException(nameof(result)); - } - - var conf = new NetworkConfiguration() - { - EnableIPV6 = true, - EnableIPV4 = true - }; - - using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger()); - - // Test included, IP6. - Collection ncSource = nm.CreateIPCollection(source.Split(',')); - Collection ncDest = nm.CreateIPCollection(dest.Split(',')); - Collection ncResult = ncSource.ThatAreContainedInNetworks(ncDest); - Collection resultCollection = nm.CreateIPCollection(result.Split(',')); - Assert.True(ncResult.Compare(resultCollection)); - } - - [Theory] - [InlineData("10.1.1.1/32", "10.1.1.1")] - [InlineData("192.168.1.254/32", "192.168.1.254/255.255.255.255")] - - public void TestEquals(string source, string dest) - { - Assert.True(IPNetAddress.Parse(source).Equals(IPNetAddress.Parse(dest))); - Assert.True(IPNetAddress.Parse(dest).Equals(IPNetAddress.Parse(source))); - } - - [Theory] - // Testing bind interfaces. // On my system eth16 is internal, eth11 external (Windows defines the indexes). // - // This test is to replicate how DNLA requests work throughout the system. + // This test is to replicate how DLNA requests work throughout the system. // User on internal network, we're bound internal and external - so result is internal. [InlineData("192.168.1.1", "eth16,eth11", false, "eth16")] @@ -357,14 +175,14 @@ 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 Collection? resultObj); // Check to see if dns resolution is working. If not, skip test. - _ = IPHost.TryParse(source, out var host); + _ = NetworkExtensions.TryParseHost(source, out var host); - if (resultObj != null && host?.HasAddress == true) + if (resultObj != null && host.Length > 0) { - result = ((IPNetAddress)resultObj[0]).ToString(true); + result = resultObj.First().Address.ToString(); var intf = nm.GetBindInterface(source, out _); Assert.Equal(intf, result); @@ -394,7 +212,7 @@ namespace Jellyfin.Networking.Tests [InlineData("jellyfin.org", "192.168.1.0/24", "eth16", false, "0.0.0.0=http://helloworld.com", "http://helloworld.com")] // User on external network, no binding - so result is the 1st external which is overriden. - [InlineData("jellyfin.org", "192.168.1.0/24", "", false, "0.0.0.0 = http://helloworld.com", "http://helloworld.com")] + [InlineData("jellyfin.org", "192.168.1.0/24", "", false, "0.0.0.0=http://helloworld.com", "http://helloworld.com")] // User assumed to be internal, no binding - so result is the 1st internal. [InlineData("", "192.168.1.0/24", "", false, "0.0.0.0=http://helloworld.com", "eth16")] @@ -426,15 +244,15 @@ 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 Collection? resultObj) && resultObj != null) { // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks). - result = ((IPNetAddress)resultObj[0]).ToString(true); + result = resultObj.First().Address.ToString(); } var intf = nm.GetBindInterface(source, out int? _); - Assert.Equal(intf, result); + Assert.Equal(result, intf); } [Theory] @@ -461,6 +279,7 @@ namespace Jellyfin.Networking.Tests [InlineData("185.10.10.10", "79.2.3.4", false)] [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) { // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.