aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Emby.Dlna/Main/DlnaEntryPoint.cs26
-rw-r--r--Emby.Server.Implementations/ApplicationHost.cs10
-rw-r--r--Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs45
-rw-r--r--Emby.Server.Implementations/Net/SocketFactory.cs13
-rw-r--r--Emby.Server.Implementations/Udp/UdpServer.cs4
-rw-r--r--Jellyfin.Networking/Configuration/NetworkConfiguration.cs153
-rw-r--r--Jellyfin.Networking/Manager/NetworkManager.cs1499
-rw-r--r--Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs26
-rw-r--r--Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs4
-rw-r--r--MediaBrowser.Common/Net/INetworkManager.cs169
-rw-r--r--MediaBrowser.Common/Net/IPData.cs69
-rw-r--r--MediaBrowser.Common/Net/IPHost.cs441
-rw-r--r--MediaBrowser.Common/Net/IPNetAddress.cs273
-rw-r--r--MediaBrowser.Common/Net/IPObject.cs355
-rw-r--r--MediaBrowser.Common/Net/NetworkExtensions.cs391
-rw-r--r--MediaBrowser.Controller/IServerApplicationHost.cs5
-rw-r--r--MediaBrowser.Model/Net/ISocketFactory.cs3
-rw-r--r--RSSDP/SsdpCommunicationsServer.cs77
-rw-r--r--RSSDP/SsdpDevicePublisher.cs5
-rw-r--r--tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs49
-rw-r--r--tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs (renamed from tests/Jellyfin.Networking.Tests/IPHostTests.cs)10
-rw-r--r--tests/Jellyfin.Networking.Tests/NetworkParseTests.cs258
-rw-r--r--tests/Jellyfin.Server.Tests/ParseNetworkTests.cs8
23 files changed, 1220 insertions, 2673 deletions
diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs
index 2dc079254..22903ec8f 100644
--- a/Emby.Dlna/Main/DlnaEntryPoint.cs
+++ b/Emby.Dlna/Main/DlnaEntryPoint.cs
@@ -11,7 +11,6 @@ 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,17 +284,20 @@ 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)));
+ // Only get bind addresses in LAN
+ var bindAddresses = _networkManager
+ .GetInternalBindAddresses()
+ .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork
+ || (i.AddressFamily == AddressFamily.InterNetworkV6 && i.Address.ScopeId != 0))
+ .ToList();
if (bindAddresses.Count == 0)
{
// No interfaces returned, so use loopback.
- bindAddresses = _networkManager.GetLoopbacks();
+ bindAddresses = _networkManager.GetLoopbacks().ToList();
}
- foreach (IPNetAddress address in bindAddresses)
+ foreach (var address in bindAddresses)
{
if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
@@ -303,24 +305,18 @@ namespace Emby.Dlna.Main
continue;
}
- // Limit to LAN addresses only
- if (!_networkManager.IsInLocalNetwork(address))
- {
- continue;
- }
-
var fullService = "urn:schemas-upnp-org:device:MediaServer:1";
- _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, address);
+ _logger.LogInformation("Registering publisher for {ResourceName} on {DeviceAddress}", fullService, address.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 c18796611..e1e83621b 100644
--- a/Emby.Server.Implementations/ApplicationHost.cs
+++ b/Emby.Server.Implementations/ApplicationHost.cs
@@ -1072,7 +1072,7 @@ namespace Emby.Server.Implementations
return PublishedServerUrl.Trim('/');
}
- string smart = NetManager.GetBindInterface(remoteAddr, out var port);
+ string smart = NetManager.GetBindAddress(remoteAddr, out var port);
return GetLocalApiUrl(smart.Trim('/'), null, port);
}
@@ -1083,7 +1083,9 @@ namespace Emby.Server.Implementations
if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
{
int? requestPort = request.Host.Port;
- if ((requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
+ if (requestPort == null
+ || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
+ || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
{
requestPort = -1;
}
@@ -1109,10 +1111,10 @@ namespace Emby.Server.Implementations
}
/// <inheritdoc/>
- 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.GetBindAddress(ipAddress, out _);
var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
int? port = !allowHttps ? HttpPort : null;
return GetLocalApiUrl(smart, scheme, port);
diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
index e45baedd7..c2ffaf1bd 100644
--- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
+++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
@@ -1,10 +1,12 @@
using System;
+using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Emby.Server.Implementations.Udp;
using Jellyfin.Networking.Configuration;
using MediaBrowser.Common.Configuration;
+using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Plugins;
using Microsoft.Extensions.Configuration;
@@ -29,11 +31,13 @@ namespace Emby.Server.Implementations.EntryPoints
private readonly IServerApplicationHost _appHost;
private readonly IConfiguration _config;
private readonly IConfigurationManager _configurationManager;
+ private readonly INetworkManager _networkManager;
+ private readonly bool _enableMultiSocketBinding;
/// <summary>
/// The UDP server.
/// </summary>
- private UdpServer? _udpServer;
+ private List<UdpServer> _udpServers;
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private bool _disposed = false;
@@ -44,16 +48,21 @@ namespace Emby.Server.Implementations.EntryPoints
/// <param name="appHost">Instance of the <see cref="IServerApplicationHost"/> interface.</param>
/// <param name="configuration">Instance of the <see cref="IConfiguration"/> interface.</param>
/// <param name="configurationManager">Instance of the <see cref="IConfigurationManager"/> interface.</param>
+ /// <param name="networkManager">Instance of the <see cref="INetworkManager"/> interface.</param>
public UdpServerEntryPoint(
ILogger<UdpServerEntryPoint> logger,
IServerApplicationHost appHost,
IConfiguration configuration,
- IConfigurationManager configurationManager)
+ IConfigurationManager configurationManager,
+ INetworkManager networkManager)
{
_logger = logger;
_appHost = appHost;
_config = configuration;
_configurationManager = configurationManager;
+ _networkManager = networkManager;
+ _udpServers = new List<UdpServer>();
+ _enableMultiSocketBinding = OperatingSystem.IsWindows() || OperatingSystem.IsLinux();
}
/// <inheritdoc />
@@ -68,8 +77,32 @@ namespace Emby.Server.Implementations.EntryPoints
try
{
- _udpServer = new UdpServer(_logger, _appHost, _config, PortNumber);
- _udpServer.Start(_cancellationTokenSource.Token);
+ if (_enableMultiSocketBinding)
+ {
+ // Add global broadcast socket
+ _udpServers.Add(new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Broadcast, PortNumber));
+
+ // Add bind address specific broadcast sockets
+ foreach (var bindAddress in _networkManager.GetInternalBindAddresses())
+ {
+ if (bindAddress.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ // Not supporting IPv6 right now
+ continue;
+ }
+
+ var broadcastAddress = NetworkExtensions.GetBroadcastAddress(bindAddress.Subnet);
+ _logger.LogDebug("Binding UDP server to {Address} on port {PortNumber}", broadcastAddress.ToString(), PortNumber);
+
+ _udpServers.Add(new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber));
+ }
+ }
+ else
+ {
+ _udpServers.Add(new UdpServer(_logger, _appHost, _config, System.Net.IPAddress.Any, PortNumber));
+ }
+
+ _udpServers.ForEach(u => u.Start(_cancellationTokenSource.Token));
}
catch (SocketException ex)
{
@@ -97,8 +130,8 @@ namespace Emby.Server.Implementations.EntryPoints
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
- _udpServer?.Dispose();
- _udpServer = null;
+ _udpServers.ForEach(s => s.Dispose());
+ _udpServers.Clear();
_disposed = true;
}
diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs
index 303875df5..e0c75698d 100644
--- a/Emby.Server.Implementations/Net/SocketFactory.cs
+++ b/Emby.Server.Implementations/Net/SocketFactory.cs
@@ -61,10 +61,15 @@ namespace Emby.Server.Implementations.Net
}
/// <inheritdoc />
- public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, int multicastTimeToLive, int localPort)
+ public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress? bindIpAddress, int multicastTimeToLive, int localPort)
{
ArgumentNullException.ThrowIfNull(ipAddress);
+ if (bindIpAddress == null)
+ {
+ bindIpAddress = IPAddress.Any;
+ }
+
if (multicastTimeToLive <= 0)
{
throw new ArgumentException("multicastTimeToLive cannot be zero or less.", nameof(multicastTimeToLive));
@@ -95,12 +100,10 @@ namespace Emby.Server.Implementations.Net
// retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
- var localIp = IPAddress.Any;
-
- retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ipAddress, localIp));
+ retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ipAddress, bindIpAddress));
retVal.MulticastLoopback = true;
- return new UdpSocket(retVal, localPort, localIp);
+ return new UdpSocket(retVal, localPort, bindIpAddress);
}
catch
{
diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs
index 937e792f5..a3bbd6df0 100644
--- a/Emby.Server.Implementations/Udp/UdpServer.cs
+++ b/Emby.Server.Implementations/Udp/UdpServer.cs
@@ -37,18 +37,20 @@ namespace Emby.Server.Implementations.Udp
/// <param name="logger">The logger.</param>
/// <param name="appHost">The application host.</param>
/// <param name="configuration">The configuration manager.</param>
+ /// <param name="bindAddress"> The bind address.</param>
/// <param name="port">The port.</param>
public UdpServer(
ILogger logger,
IServerApplicationHost appHost,
IConfiguration configuration,
+ IPAddress bindAddress,
int port)
{
_logger = logger;
_appHost = appHost;
_config = configuration;
- _endpoint = new IPEndPoint(IPAddress.Any, port);
+ _endpoint = new IPEndPoint(bindAddress, port);
_udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs
index 361dbc814..f90419851 100644
--- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs
+++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs
@@ -22,21 +22,6 @@ namespace Jellyfin.Networking.Configuration
private string _baseUrl = string.Empty;
/// <summary>
- /// Gets or sets a value indicating whether the server should force connections over HTTPS.
- /// </summary>
- public bool RequireHttps { get; set; }
-
- /// <summary>
- /// Gets or sets the filesystem path of an X.509 certificate to use for SSL.
- /// </summary>
- public string CertificatePath { get; set; } = string.Empty;
-
- /// <summary>
- /// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>.
- /// </summary>
- public string CertificatePassword { get; set; } = string.Empty;
-
- /// <summary>
/// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at.
/// </summary>
public string BaseUrl
@@ -70,24 +55,6 @@ namespace Jellyfin.Networking.Configuration
}
/// <summary>
- /// Gets or sets the public HTTPS port.
- /// </summary>
- /// <value>The public HTTPS port.</value>
- public int PublicHttpsPort { get; set; } = DefaultHttpsPort;
-
- /// <summary>
- /// Gets or sets the HTTP server port number.
- /// </summary>
- /// <value>The HTTP server port number.</value>
- public int HttpServerPortNumber { get; set; } = DefaultHttpPort;
-
- /// <summary>
- /// Gets or sets the HTTPS server port number.
- /// </summary>
- /// <value>The HTTPS server port number.</value>
- public int HttpsPortNumber { get; set; } = DefaultHttpsPort;
-
- /// <summary>
/// Gets or sets a value indicating whether to use HTTPS.
/// </summary>
/// <remarks>
@@ -97,139 +64,113 @@ namespace Jellyfin.Networking.Configuration
public bool EnableHttps { get; set; }
/// <summary>
- /// Gets or sets the public mapped port.
- /// </summary>
- /// <value>The public mapped port.</value>
- public int PublicPort { get; set; } = DefaultHttpPort;
-
- /// <summary>
- /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.
- /// </summary>
- public bool UPnPCreateHttpPortMap { get; set; }
-
- /// <summary>
- /// Gets or sets the UDPPortRange.
- /// </summary>
- public string UDPPortRange { get; set; } = string.Empty;
-
- /// <summary>
- /// Gets or sets a value indicating whether gets or sets IPV6 capability.
- /// </summary>
- public bool EnableIPV6 { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether gets or sets IPV4 capability.
- /// </summary>
- public bool EnableIPV4 { get; set; } = true;
-
- /// <summary>
- /// Gets or sets a value indicating whether detailed SSDP logs are sent to the console/log.
- /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to have any effect.
+ /// Gets or sets a value indicating whether the server should force connections over HTTPS.
/// </summary>
- public bool EnableSSDPTracing { get; set; }
+ public bool RequireHttps { get; set; }
/// <summary>
- /// Gets or sets the SSDPTracingFilter
- /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log.
- /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work.
+ /// Gets or sets the filesystem path of an X.509 certificate to use for SSL.
/// </summary>
- public string SSDPTracingFilter { get; set; } = string.Empty;
+ public string CertificatePath { get; set; } = string.Empty;
/// <summary>
- /// Gets or sets the number of times SSDP UDP messages are sent.
+ /// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>.
/// </summary>
- public int UDPSendCount { get; set; } = 2;
+ public string CertificatePassword { get; set; } = string.Empty;
/// <summary>
- /// Gets or sets the delay between each groups of SSDP messages (in ms).
+ /// Gets or sets the HTTPS server port number.
/// </summary>
- public int UDPSendDelay { get; set; } = 100;
+ /// <value>The HTTPS server port number.</value>
+ public int HttpsPortNumber { get; set; } = DefaultHttpsPort;
/// <summary>
- /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding.
+ /// Gets or sets the public HTTPS port.
/// </summary>
- public bool IgnoreVirtualInterfaces { get; set; } = true;
+ /// <value>The public HTTPS port.</value>
+ public int PublicHttpsPort { get; set; } = DefaultHttpsPort;
/// <summary>
- /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>.
+ /// Gets or sets the HTTP server port number.
/// </summary>
- public string VirtualInterfaceNames { get; set; } = "vEthernet*";
+ /// <value>The HTTP server port number.</value>
+ public int HttpServerPortNumber { get; set; } = DefaultHttpPort;
/// <summary>
- /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor.
+ /// Gets or sets the public mapped port.
/// </summary>
- public int GatewayMonitorPeriod { get; set; } = 60;
+ /// <value>The public mapped port.</value>
+ public int PublicPort { get; set; } = DefaultHttpPort;
/// <summary>
- /// Gets a value indicating whether multi-socket binding is available.
+ /// Gets or sets a value indicating whether Autodiscovery is enabled.
/// </summary>
- public bool EnableMultiSocketBinding { get; } = true;
+ public bool AutoDiscovery { get; set; } = true;
/// <summary>
- /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network.
- /// Depending on the address range implemented ULA ranges might not be used.
+ /// Gets or sets a value indicating whether to enable automatic port forwarding.
/// </summary>
- public bool TrustAllIP6Interfaces { get; set; }
+ public bool EnableUPnP { get; set; }
/// <summary>
- /// Gets or sets the ports that HDHomerun uses.
+ /// Gets or sets a value indicating whether IPv6 is enabled or not.
/// </summary>
- public string HDHomerunPortRange { get; set; } = string.Empty;
+ public bool EnableIPV4 { get; set; } = true;
/// <summary>
- /// Gets or sets the PublishedServerUriBySubnet
- /// Gets or sets PublishedServerUri to advertise for specific subnets.
+ /// Gets or sets a value indicating whether IPv6 is enabled or not.
/// </summary>
- public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>();
+ public bool EnableIPV6 { get; set; }
/// <summary>
- /// Gets or sets a value indicating whether Autodiscovery tracing is enabled.
+ /// Gets or sets a value indicating whether access outside of the LAN is permitted.
/// </summary>
- public bool AutoDiscoveryTracing { get; set; }
+ public bool EnableRemoteAccess { get; set; } = true;
/// <summary>
- /// Gets or sets a value indicating whether Autodiscovery is enabled.
+ /// Gets or sets the subnets that are deemed to make up the LAN.
/// </summary>
- public bool AutoDiscovery { get; set; } = true;
+ public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>();
/// <summary>
- /// Gets or sets the filter for remote IP connectivity. Used in conjunction with <seealso cref="IsRemoteIPFilterBlacklist"/>.
+ /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.
/// </summary>
- public string[] RemoteIPFilter { get; set; } = Array.Empty<string>();
+ public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>();
/// <summary>
- /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist.
+ /// Gets or sets the known proxies. If the proxy is a network, it's added to the KnownNetworks.
/// </summary>
- public bool IsRemoteIPFilterBlacklist { get; set; }
+ public string[] KnownProxies { get; set; } = Array.Empty<string>();
/// <summary>
- /// Gets or sets a value indicating whether to enable automatic port forwarding.
+ /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding.
/// </summary>
- public bool EnableUPnP { get; set; }
+ public bool IgnoreVirtualInterfaces { get; set; } = true;
/// <summary>
- /// Gets or sets a value indicating whether access outside of the LAN is permitted.
+ /// Gets or sets a value indicating the interface name prefixes that should be ignored. The list can be comma separated and values are case-insensitive. <seealso cref="IgnoreVirtualInterfaces"/>.
/// </summary>
- public bool EnableRemoteAccess { get; set; } = true;
+ public string[] VirtualInterfaceNames { get; set; } = new string[] { "veth" };
/// <summary>
- /// Gets or sets the subnets that are deemed to make up the LAN.
+ /// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests.
/// </summary>
- public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>();
+ public bool EnablePublishedServerUriByRequest { get; set; } = false;
/// <summary>
- /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.
+ /// Gets or sets the PublishedServerUriBySubnet
+ /// Gets or sets PublishedServerUri to advertise for specific subnets.
/// </summary>
- public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>();
+ public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>();
/// <summary>
- /// Gets or sets the known proxies. If the proxy is a network, it's added to the KnownNetworks.
+ /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>.
/// </summary>
- public string[] KnownProxies { get; set; } = Array.Empty<string>();
+ public string[] RemoteIPFilter { get; set; } = Array.Empty<string>();
/// <summary>
- /// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests.
+ /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist.
/// </summary>
- public bool EnablePublishedServerUriByRequest { get; set; } = false;
+ public bool IsRemoteIPFilterBlacklist { get; set; }
}
}
diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs
index 5520e2f04..031858206 100644
--- a/Jellyfin.Networking/Manager/NetworkManager.cs
+++ b/Jellyfin.Networking/Manager/NetworkManager.cs
@@ -1,41 +1,29 @@
using System;
using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
-using System.Threading.Tasks;
+using System.Threading;
using Jellyfin.Networking.Configuration;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Networking.Manager
{
/// <summary>
/// Class to take care of network interface management.
- /// Note: The normal collection methods and properties will not work with Collection{IPObject}. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>.
/// </summary>
public class NetworkManager : INetworkManager, IDisposable
{
/// <summary>
- /// Contains the description of the interface along with its index.
- /// </summary>
- private readonly Dictionary<string, int> _interfaceNames;
-
- /// <summary>
/// Threading lock for network properties.
/// </summary>
- private readonly object _intLock = new object();
-
- /// <summary>
- /// List of all interface addresses and masks.
- /// </summary>
- private readonly Collection<IPObject> _interfaceAddresses;
+ private readonly object _initLock;
/// <summary>
/// List of all interface MAC addresses.
@@ -46,12 +34,14 @@ namespace Jellyfin.Networking.Manager
private readonly IConfigurationManager _configurationManager;
- private readonly object _eventFireLock;
+ private readonly object _networkEventLock;
/// <summary>
- /// Holds the bind address overrides.
+ /// Holds the published server URLs and the IPs to use them on.
/// </summary>
- private readonly Dictionary<IPNetAddress, string> _publishedServerUrls;
+ private readonly Dictionary<IPData, string> _publishedServerUrls;
+
+ private List<IPNetwork> _remoteAddressFilter;
/// <summary>
/// Used to stop "event-racing conditions".
@@ -59,35 +49,20 @@ namespace Jellyfin.Networking.Manager
private bool _eventfire;
/// <summary>
- /// Unfiltered user defined LAN subnets. (<see cref="NetworkConfiguration.LocalNetworkSubnets"/>)
- /// or internal interface network subnets if undefined by user.
- /// </summary>
- private Collection<IPObject> _lanSubnets;
-
- /// <summary>
- /// User defined list of subnets to excluded from the LAN.
- /// </summary>
- private Collection<IPObject> _excludedSubnets;
-
- /// <summary>
- /// List of interface addresses to bind the WS.
+ /// Dictionary containing interface addresses and their subnets.
/// </summary>
- private Collection<IPObject> _bindAddresses;
+ private List<IPData> _interfaces;
/// <summary>
- /// List of interface addresses to exclude from bind.
- /// </summary>
- private Collection<IPObject> _bindExclusions;
-
- /// <summary>
- /// Caches list of all internal filtered interface addresses and masks.
+ /// Unfiltered user defined LAN subnets (<see cref="NetworkConfiguration.LocalNetworkSubnets"/>)
+ /// or internal interface network subnets if undefined by user.
/// </summary>
- private Collection<IPObject> _internalInterfaces;
+ private List<IPNetwork> _lanSubnets;
/// <summary>
- /// Flag set when no custom LAN has been defined in the configuration.
+ /// User defined list of subnets to excluded from the LAN.
/// </summary>
- private bool _usingPrivateAddresses;
+ private List<IPNetwork> _excludedSubnets;
/// <summary>
/// True if this object is disposed.
@@ -102,14 +77,17 @@ namespace Jellyfin.Networking.Manager
#pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in UpdateSettings function. Compiler doesn't yet recognise this.
public NetworkManager(IConfigurationManager configurationManager, ILogger<NetworkManager> logger)
{
- _logger = logger ?? throw new ArgumentNullException(nameof(logger));
- _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager));
+ ArgumentNullException.ThrowIfNull(logger);
+ ArgumentNullException.ThrowIfNull(configurationManager);
- _interfaceAddresses = new Collection<IPObject>();
+ _logger = logger;
+ _configurationManager = configurationManager;
+ _initLock = new();
+ _interfaces = new List<IPData>();
_macAddresses = new List<PhysicalAddress>();
- _interfaceNames = new Dictionary<string, int>();
- _publishedServerUrls = new Dictionary<IPNetAddress, string>();
- _eventFireLock = new object();
+ _publishedServerUrls = new Dictionary<IPData, string>();
+ _networkEventLock = new object();
+ _remoteAddressFilter = new List<IPNetwork>();
UpdateSettings(_configurationManager.GetNetworkConfiguration());
@@ -131,46 +109,24 @@ namespace Jellyfin.Networking.Manager
public static string MockNetworkSettings { get; set; } = string.Empty;
/// <summary>
- /// Gets or sets a value indicating whether IP6 is enabled.
+ /// Gets a value indicating whether IP4 is enabled.
/// </summary>
- public bool IsIP6Enabled { get; set; }
+ public bool IsIpv4Enabled => _configurationManager.GetNetworkConfiguration().EnableIPV4;
/// <summary>
- /// Gets or sets a value indicating whether IP4 is enabled.
+ /// Gets a value indicating whether IP6 is enabled.
/// </summary>
- public bool IsIP4Enabled { get; set; }
-
- /// <inheritdoc/>
- public Collection<IPObject> RemoteAddressFilter { get; private set; }
+ public bool IsIpv6Enabled => _configurationManager.GetNetworkConfiguration().EnableIPV6;
/// <summary>
/// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
/// </summary>
- public bool TrustAllIP6Interfaces { get; internal set; }
+ public bool TrustAllIpv6Interfaces { get; private set; }
/// <summary>
/// Gets the Published server override list.
/// </summary>
- public Dictionary<IPNetAddress, string> PublishedServerUrls => _publishedServerUrls;
-
- /// <summary>
- /// Creates a new network collection.
- /// </summary>
- /// <param name="source">Items to assign the collection, or null.</param>
- /// <returns>The collection created.</returns>
- public static Collection<IPObject> CreateCollection(IEnumerable<IPObject>? source = null)
- {
- var result = new Collection<IPObject>();
- if (source is not null)
- {
- foreach (var item in source)
- {
- result.AddItem(item, false);
- }
- }
-
- return result;
- }
+ public Dictionary<IPData, string> PublishedServerUrls => _publishedServerUrls;
/// <inheritdoc/>
public void Dispose()
@@ -179,409 +135,356 @@ namespace Jellyfin.Networking.Manager
GC.SuppressFinalize(this);
}
- /// <inheritdoc/>
- public IReadOnlyCollection<PhysicalAddress> GetMacAddresses()
+ /// <summary>
+ /// Handler for network change events.
+ /// </summary>
+ /// <param name="sender">Sender.</param>
+ /// <param name="e">A <see cref="NetworkAvailabilityEventArgs"/> containing network availability information.</param>
+ private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e)
{
- // Populated in construction - so always has values.
- return _macAddresses;
+ _logger.LogDebug("Network availability changed.");
+ HandleNetworkChange();
}
- /// <inheritdoc/>
- public bool IsGatewayInterface(IPObject? addressObj)
+ /// <summary>
+ /// Handler for network change events.
+ /// </summary>
+ /// <param name="sender">Sender.</param>
+ /// <param name="e">An <see cref="EventArgs"/>.</param>
+ private void OnNetworkAddressChanged(object? sender, EventArgs e)
{
- var address = addressObj?.Address ?? IPAddress.None;
- return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0);
+ _logger.LogDebug("Network address change detected.");
+ HandleNetworkChange();
}
- /// <inheritdoc/>
- public bool IsGatewayInterface(IPAddress? addressObj)
+ /// <summary>
+ /// Triggers our event, and re-loads interface information.
+ /// </summary>
+ private void HandleNetworkChange()
{
- return _internalInterfaces.Any(i => i.Address.Equals(addressObj ?? IPAddress.None) && i.Tag < 0);
+ lock (_networkEventLock)
+ {
+ if (!_eventfire)
+ {
+ _logger.LogDebug("Network Address Change Event.");
+ // As network events tend to fire one after the other only fire once every second.
+ _eventfire = true;
+ OnNetworkChange();
+ }
+ }
}
- /// <inheritdoc/>
- public Collection<IPObject> GetLoopbacks()
+ /// <summary>
+ /// Waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession.
+ /// </summary>
+ private void OnNetworkChange()
{
- Collection<IPObject> nc = new Collection<IPObject>();
- if (IsIP4Enabled)
+ try
{
- nc.AddItem(IPAddress.Loopback);
- }
+ Thread.Sleep(2000);
+ var networkConfig = _configurationManager.GetNetworkConfiguration();
+ InitialiseLan(networkConfig);
+ InitialiseInterfaces();
+ EnforceBindSettings(networkConfig);
- if (IsIP6Enabled)
+ NetworkChanged?.Invoke(this, EventArgs.Empty);
+ }
+ finally
{
- nc.AddItem(IPAddress.IPv6Loopback);
+ _eventfire = false;
}
-
- return nc;
- }
-
- /// <inheritdoc/>
- public bool IsExcluded(IPAddress ip)
- {
- return _excludedSubnets.ContainsAddress(ip);
- }
-
- /// <inheritdoc/>
- public bool IsExcluded(EndPoint ip)
- {
- return ip is not null && IsExcluded(((IPEndPoint)ip).Address);
}
- /// <inheritdoc/>
- public Collection<IPObject> CreateIPCollection(string[] values, bool negated = false)
+ /// <summary>
+ /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state.
+ /// Generate a list of all active mac addresses that aren't loopback addresses.
+ /// </summary>
+ private void InitialiseInterfaces()
{
- Collection<IPObject> col = new Collection<IPObject>();
- if (values is null)
+ lock (_initLock)
{
- return col;
- }
+ _logger.LogDebug("Refreshing interfaces.");
- for (int a = 0; a < values.Length; a++)
- {
- string v = values[a].Trim();
+ _interfaces.Clear();
+ _macAddresses.Clear();
try
{
- if (v.StartsWith('!'))
+ var nics = NetworkInterface.GetAllNetworkInterfaces()
+ .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up);
+
+ foreach (NetworkInterface adapter in nics)
{
- if (negated)
+ try
{
- AddToCollection(col, v[1..]);
+ var ipProperties = adapter.GetIPProperties();
+ var mac = adapter.GetPhysicalAddress();
+
+ // Populate MAC list
+ if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && PhysicalAddress.None.Equals(mac))
+ {
+ _macAddresses.Add(mac);
+ }
+
+ // Populate interface list
+ foreach (var info in ipProperties.UnicastAddresses)
+ {
+ if (IsIpv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name);
+ interfaceObject.Index = ipProperties.GetIPv4Properties().Index;
+ interfaceObject.Name = adapter.Name;
+
+ _interfaces.Add(interfaceObject);
+ }
+ else if (IsIpv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength), adapter.Name);
+ interfaceObject.Index = ipProperties.GetIPv6Properties().Index;
+ interfaceObject.Name = adapter.Name;
+
+ _interfaces.Add(interfaceObject);
+ }
+ }
+ }
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch (Exception ex)
+#pragma warning restore CA1031 // Do not catch general exception types
+ {
+ // Ignore error, and attempt to continue.
+ _logger.LogError(ex, "Error encountered parsing interfaces.");
}
- }
- else if (!negated)
- {
- AddToCollection(col, v);
}
}
- catch (ArgumentException e)
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch (Exception ex)
+#pragma warning restore CA1031 // Do not catch general exception types
{
- _logger.LogWarning(e, "Ignoring LAN value {Value}.", v);
+ _logger.LogError(ex, "Error obtaining interfaces.");
}
- }
-
- return col;
- }
-
- /// <inheritdoc/>
- public Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false)
- {
- int count = _bindAddresses.Count;
- if (count == 0)
- {
- if (_bindExclusions.Count > 0)
+ if (_interfaces.Count == 0)
{
- // Return all the interfaces except the ones specifically excluded.
- return _interfaceAddresses.Exclude(_bindExclusions, false);
- }
+ _logger.LogWarning("No interface information available. Using loopback interface(s).");
- if (individualInterfaces)
- {
- return new Collection<IPObject>(_interfaceAddresses);
- }
-
- // No bind address and no exclusions, so listen on all interfaces.
- Collection<IPObject> result = new Collection<IPObject>();
+ if (IsIpv4Enabled && !IsIpv6Enabled)
+ {
+ _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo"));
+ }
- if (IsIP6Enabled && IsIP4Enabled)
- {
- // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any
- result.AddItem(IPAddress.IPv6Any);
- }
- else if (IsIP4Enabled)
- {
- result.AddItem(IPAddress.Any);
- }
- else if (IsIP6Enabled)
- {
- // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses.
- foreach (var iface in _interfaceAddresses)
+ if (!IsIpv4Enabled && IsIpv6Enabled)
{
- if (iface.AddressFamily == AddressFamily.InterNetworkV6)
- {
- result.AddItem(iface.Address);
- }
+ _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo"));
}
}
- return result;
+ _logger.LogDebug("Discovered {0} interfaces.", _interfaces.Count);
+ _logger.LogDebug("Interfaces addresses: {0}", _interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString()));
}
-
- // Remove any excluded bind interfaces.
- return _bindAddresses.Exclude(_bindExclusions, false);
- }
-
- /// <inheritdoc/>
- public string GetBindInterface(string source, out int? port)
- {
- if (!string.IsNullOrEmpty(source) && IPHost.TryParse(source, out IPHost host))
- {
- return GetBindInterface(host, out port);
- }
-
- return GetBindInterface(IPHost.None, out port);
}
- /// <inheritdoc/>
- public string GetBindInterface(IPAddress source, out int? port)
- {
- return GetBindInterface(new IPNetAddress(source), out port);
- }
-
- /// <inheritdoc/>
- public string GetBindInterface(HttpRequest source, out int? port)
+ /// <summary>
+ /// Initialises internal LAN cache.
+ /// </summary>
+ private void InitialiseLan(NetworkConfiguration config)
{
- string result;
-
- if (source is not null && IPHost.TryParse(source.Host.Host, out IPHost host))
+ lock (_initLock)
{
- result = GetBindInterface(host, out port);
- port ??= source.Host.Port;
- }
- else
- {
- result = GetBindInterface(IPNetAddress.None, out port);
- port ??= source?.Host.Port;
- }
-
- return result;
- }
-
- /// <inheritdoc/>
- public string GetBindInterface(IPObject source, out int? port)
- {
- port = null;
- ArgumentNullException.ThrowIfNull(source);
+ _logger.LogDebug("Refreshing LAN information.");
- // Do we have a source?
- bool haveSource = !source.Address.Equals(IPAddress.None);
- bool isExternal = false;
+ // Get configuration options
+ string[] subnets = config.LocalNetworkSubnets;
- 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.");
- }
+ _ = NetworkExtensions.TryParseToSubnets(subnets, out _lanSubnets, false);
+ _ = NetworkExtensions.TryParseToSubnets(subnets, out _excludedSubnets, true);
- if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork)
+ if (_lanSubnets.Count == 0)
{
- _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
- }
+ // If no LAN addresses are specified, all private subnets and Loopback are deemed to be the LAN
+ _logger.LogDebug("Using LAN interface addresses as user provided no LAN details.");
- isExternal = !IsInLocalNetwork(source);
+ if (IsIpv6Enabled)
+ {
+ _lanSubnets.Add(new IPNetwork(IPAddress.IPv6Loopback, 128)); // RFC 4291 (Loopback)
+ _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // RFC 4291 (Site local)
+ _lanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // RFC 4193 (Unique local)
+ }
- if (MatchesPublishedServerUrl(source, isExternal, out string res, out port))
- {
- _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port);
- return res;
+ if (IsIpv4Enabled)
+ {
+ _lanSubnets.Add(new IPNetwork(IPAddress.Loopback, 8)); // RFC 5735 (Loopback)
+ _lanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); // RFC 1918 (private)
+ _lanSubnets.Add(new IPNetwork(IPAddress.Parse("172.16.0.0"), 12)); // RFC 1918 (private)
+ _lanSubnets.Add(new IPNetwork(IPAddress.Parse("192.168.0.0"), 16)); // RFC 1918 (private)
+ }
}
- }
-
- _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;
+ _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));
}
+ }
- // Get the first LAN interface address that isn't a loopback.
- var interfaces = CreateCollection(
- _interfaceAddresses
- .Exclude(_bindExclusions, false)
- .Where(IsInLocalNetwork)
- .OrderBy(p => p.Tag));
-
- if (interfaces.Count > 0)
+ /// <summary>
+ /// Enforce bind addresses and exclusions on available interfaces.
+ /// </summary>
+ private void EnforceBindSettings(NetworkConfiguration config)
+ {
+ lock (_initLock)
{
- if (haveSource)
+ // Respect explicit bind addresses
+ var localNetworkAddresses = config.LocalNetworkAddresses;
+ if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses.First()))
{
- foreach (var intf in interfaces)
+ var bindAddresses = localNetworkAddresses.Select(p => NetworkExtensions.TryParseToSubnet(p, out var network)
+ ? network.Prefix
+ : (_interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase))
+ .Select(x => x.Address)
+ .FirstOrDefault() ?? IPAddress.None))
+ .ToList();
+ bindAddresses.RemoveAll(x => x == IPAddress.None);
+ _interfaces = _interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList();
+
+ if (bindAddresses.Contains(IPAddress.Loopback))
{
- if (intf.Address.Equals(source.Address))
- {
- result = FormatIP6String(intf.Address);
- _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface. {Result}", source, result);
- return result;
- }
+ _interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo"));
}
- // Does the request originate in one of the interface subnets?
- // (For systems with multiple internal network cards, and multiple subnets)
- foreach (var intf in interfaces)
+ if (bindAddresses.Contains(IPAddress.IPv6Loopback))
{
- if (intf.Contains(source))
- {
- result = FormatIP6String(intf.Address);
- _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result);
- return result;
- }
+ _interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo"));
}
}
- result = FormatIP6String(interfaces.First().Address);
- _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result);
- return result;
- }
-
- // There isn't any others, so we'll use the loopback.
- result = IsIP6Enabled ? "::1" : "127.0.0.1";
- _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result);
- return result;
- }
+ // Remove all interfaces matching any virtual machine interface prefix
+ if (config.IgnoreVirtualInterfaces)
+ {
+ // Remove potentially exisiting * and split config string into prefixes
+ var virtualInterfacePrefixes = config.VirtualInterfaceNames
+ .Select(i => i.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase));
- /// <inheritdoc/>
- public Collection<IPObject> GetInternalBindAddresses()
- {
- int count = _bindAddresses.Count;
+ // Check all interfaces for matches against the prefixes and remove them
+ if (_interfaces.Count > 0)
+ {
+ foreach (var virtualInterfacePrefix in virtualInterfacePrefixes)
+ {
+ _interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase));
+ }
+ }
+ }
- if (count == 0)
- {
- if (_bindExclusions.Count > 0)
+ // Remove all IPv4 interfaces if IPv4 is disabled
+ if (!IsIpv4Enabled)
{
- // Return all the internal interfaces except the ones excluded.
- return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p)));
+ _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork);
}
- // No bind address, so return all internal interfaces.
- return CreateCollection(_internalInterfaces);
- }
-
- return new Collection<IPObject>(_bindAddresses.Where(a => IsInLocalNetwork(a)).ToArray());
- }
-
- /// <inheritdoc/>
- public bool IsInLocalNetwork(IPObject address)
- {
- return IsInLocalNetwork(address.Address);
- }
-
- /// <inheritdoc/>
- public bool IsInLocalNetwork(string address)
- {
- return IPHost.TryParse(address, out IPHost ipHost) && IsInLocalNetwork(ipHost);
- }
-
- /// <inheritdoc/>
- public bool IsInLocalNetwork(IPAddress address)
- {
- ArgumentNullException.ThrowIfNull(address);
-
- if (address.Equals(IPAddress.None))
- {
- return false;
- }
+ // Remove all IPv6 interfaces if IPv6 is disabled
+ if (!IsIpv6Enabled)
+ {
+ _interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6);
+ }
- // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
- if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
- {
- return true;
+ _logger.LogInformation("Using bind addresses: {0}", _interfaces.OrderByDescending(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.Address));
}
-
- // As private addresses can be redefined by Configuration.LocalNetworkAddresses
- return IPAddress.IsLoopback(address) || (_lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address));
}
- /// <inheritdoc/>
- public bool IsPrivateAddressRange(IPObject address)
+ /// <summary>
+ /// Initialises the remote address values.
+ /// </summary>
+ private void InitialiseRemote(NetworkConfiguration config)
{
- ArgumentNullException.ThrowIfNull(address);
-
- // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
- if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
+ lock (_initLock)
{
- return true;
- }
- else
- {
- return address.IsPrivateAddressRange();
- }
- }
-
- /// <inheritdoc/>
- public bool IsExcludedInterface(IPAddress address)
- {
- return _bindExclusions.ContainsAddress(address);
- }
+ // 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
+ _ = NetworkExtensions.TryParseToSubnets(remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray(), out _remoteAddressFilter, false);
- /// <inheritdoc/>
- public Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null)
- {
- if (filter is null)
- {
- return _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks();
+ // 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));
+ }
+ }
+ }
}
-
- return _lanSubnets.Exclude(filter, true);
- }
-
- /// <inheritdoc/>
- public bool IsValidInterfaceAddress(IPAddress address)
- {
- return _interfaceAddresses.ContainsAddress(address);
}
- /// <inheritdoc/>
- public bool TryParseInterface(string token, out Collection<IPObject>? result)
+ /// <summary>
+ /// Parses the user defined overrides into the dictionary object.
+ /// Overrides are the equivalent of localised publishedServerUrl, enabling
+ /// different addresses to be advertised over different subnets.
+ /// format is subnet=ipaddress|host|uri
+ /// when subnet = 0.0.0.0, any external address matches.
+ /// </summary>
+ private void InitialiseOverrides(NetworkConfiguration config)
{
- result = null;
- if (string.IsNullOrEmpty(token))
+ lock (_initLock)
{
- return false;
- }
-
- if (_interfaceNames is not null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index))
- {
- result = new Collection<IPObject>();
-
- _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token);
+ _publishedServerUrls.Clear();
+ string[] overrides = config.PublishedServerUriBySubnet;
- // Replace interface tags with the interface IP's.
- foreach (IPNetAddress iface in _interfaceAddresses)
+ foreach (var entry in overrides)
{
- if (Math.Abs(iface.Tag) == index
- && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
- || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
+ var parts = entry.Split('=');
+ if (parts.Length != 2)
{
- result.AddItem(iface, false);
+ _logger.LogError("Unable to parse bind override: {Entry}", entry);
+ }
+ else
+ {
+ var replacement = parts[1].Trim();
+ var identifier = parts[0];
+ if (string.Equals(identifier, "all", StringComparison.OrdinalIgnoreCase))
+ {
+ _publishedServerUrls[new IPData(IPAddress.Broadcast, null)] = replacement;
+ }
+ else if (string.Equals(identifier, "external", StringComparison.OrdinalIgnoreCase))
+ {
+ _publishedServerUrls[new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0))] = replacement;
+ _publishedServerUrls[new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0))] = replacement;
+ }
+ else if (string.Equals(identifier, "internal", StringComparison.OrdinalIgnoreCase))
+ {
+ foreach (var lan in _lanSubnets)
+ {
+ var lanPrefix = lan.Prefix;
+ _publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement;
+ }
+ }
+ else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result != null)
+ {
+ var data = new IPData(result.Prefix, result);
+ _publishedServerUrls[data] = replacement;
+ }
+ else if (TryParseInterface(identifier, out var ifaces))
+ {
+ foreach (var iface in ifaces)
+ {
+ _publishedServerUrls[iface] = replacement;
+ }
+ }
+ else
+ {
+ _logger.LogError("Unable to parse bind override: {Entry}", entry);
+ }
}
}
-
- return true;
}
-
- return false;
}
- /// <inheritdoc/>
- public bool HasRemoteAccess(IPAddress remoteIp)
+ private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt)
{
- var config = _configurationManager.GetNetworkConfiguration();
- if (config.EnableRemoteAccess)
+ if (evt.Key.Equals("network", StringComparison.Ordinal))
{
- // 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;
+ UpdateSettings((NetworkConfiguration)evt.NewConfiguration);
}
-
- return true;
}
/// <summary>
@@ -590,18 +493,12 @@ namespace Jellyfin.Networking.Manager
/// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param>
public void UpdateSettings(object configuration)
{
- NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration));
-
- IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4;
- IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6;
+ ArgumentNullException.ThrowIfNull(configuration);
- if (!IsIP6Enabled && !IsIP4Enabled)
- {
- _logger.LogError("IPv4 and IPv6 cannot both be disabled.");
- IsIP4Enabled = true;
- }
+ var config = (NetworkConfiguration)configuration;
- TrustAllIP6Interfaces = config.TrustAllIP6Interfaces;
+ InitialiseLan(config);
+ InitialiseRemote(config);
if (string.IsNullOrEmpty(MockNetworkSettings))
{
@@ -614,17 +511,25 @@ namespace Jellyfin.Networking.Manager
foreach (var details in interfaceList)
{
var parts = details.Split(',');
- var address = IPNetAddress.Parse(parts[0]);
- var index = int.Parse(parts[1], CultureInfo.InvariantCulture);
- address.Tag = index;
- _interfaceAddresses.AddItem(address, false);
- _interfaceNames[parts[2]] = Math.Abs(index);
+ if (NetworkExtensions.TryParseToSubnet(parts[0], out var subnet))
+ {
+ var address = subnet.Prefix;
+ var index = int.Parse(parts[1], CultureInfo.InvariantCulture);
+ if (address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ var data = new IPData(address, subnet, parts[2]);
+ data.Index = index;
+ _interfaces.Add(data);
+ }
+ }
+ else
+ {
+ _logger.LogWarning("Could not parse mock interface settings: {Part}", details);
+ }
}
}
- InitialiseLAN(config);
- InitialiseBind(config);
- InitialiseRemote(config);
+ EnforceBindSettings(config);
InitialiseOverrides(config);
}
@@ -647,546 +552,350 @@ namespace Jellyfin.Networking.Manager
}
}
- /// <summary>
- /// Tries to identify the string and return an object of that class.
- /// </summary>
- /// <param name="addr">String to parse.</param>
- /// <param name="result">IPObject to return.</param>
- /// <returns><c>true</c> if the value parsed successfully, <c>false</c> otherwise.</returns>
- private static bool TryParse(string addr, out IPObject result)
+ /// <inheritdoc/>
+ public bool TryParseInterface(string intf, out List<IPData> result)
{
- if (!string.IsNullOrEmpty(addr))
+ result = new List<IPData>();
+ if (string.IsNullOrEmpty(intf))
{
- // Is it an IP address
- if (IPNetAddress.TryParse(addr, out IPNetAddress nw))
- {
- result = nw;
- return true;
- }
+ return false;
+ }
- if (IPHost.TryParse(addr, out IPHost h))
+ if (_interfaces != null)
+ {
+ // Match all interfaces starting with names starting with token
+ var matchedInterfaces = _interfaces.Where(s => s.Name.Equals(intf, StringComparison.OrdinalIgnoreCase)).OrderBy(x => x.Index);
+ if (matchedInterfaces.Any())
{
- result = h;
+ _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;
}
}
- result = IPNetAddress.None;
return false;
}
- /// <summary>
- /// Converts an IPAddress into a string.
- /// Ipv6 addresses are returned in [ ], with their scope removed.
- /// </summary>
- /// <param name="address">Address to convert.</param>
- /// <returns>URI safe conversion of the address.</returns>
- private static string FormatIP6String(IPAddress address)
+ /// <inheritdoc/>
+ public bool HasRemoteAccess(IPAddress remoteIp)
{
- var str = address.ToString();
- if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ var config = _configurationManager.GetNetworkConfiguration();
+ if (config.EnableRemoteAccess)
{
- int i = str.IndexOf("%", StringComparison.OrdinalIgnoreCase);
- if (i != -1)
+ // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
+ // If left blank, all remote addresses will be allowed.
+ if (_remoteAddressFilter.Any() && !_lanSubnets.Any(x => x.Contains(remoteIp)))
{
- str = str.Substring(0, i);
- }
+ // remoteAddressFilter is a whitelist or blacklist.
+ var matches = _remoteAddressFilter.Count(remoteNetwork => remoteNetwork.Contains(remoteIp));
+ if ((!config.IsRemoteIPFilterBlacklist && matches > 0)
+ || (config.IsRemoteIPFilterBlacklist && matches == 0))
+ {
+ return true;
+ }
- return $"[{str}]";
+ return false;
+ }
+ }
+ else if (!_lanSubnets.Any(x => x.Contains(remoteIp)))
+ {
+ // Remote not enabled. So everyone should be LAN.
+ return false;
}
- return str;
+ return true;
}
- private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt)
+ /// <inheritdoc/>
+ public IReadOnlyList<PhysicalAddress> GetMacAddresses()
{
- if (evt.Key.Equals(NetworkConfigurationStore.StoreKey, StringComparison.Ordinal))
- {
- UpdateSettings((NetworkConfiguration)evt.NewConfiguration);
- }
+ // Populated in construction - so always has values.
+ return _macAddresses;
}
- /// <summary>
- /// Checks the string to see if it matches any interface names.
- /// </summary>
- /// <param name="token">String to check.</param>
- /// <param name="index">Interface index numbers that match.</param>
- /// <returns><c>true</c> if an interface name matches the token, <c>False</c> otherwise.</returns>
- private bool TryGetInterfaces(string token, [NotNullWhen(true)] out List<int>? index)
+ /// <inheritdoc/>
+ public IReadOnlyList<IPData> GetLoopbacks()
{
- index = null;
-
- // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
- // Null check required here for automated testing.
- if (_interfaceNames is not null && token.Length > 1)
+ var loopbackNetworks = new List<IPData>();
+ if (IsIpv4Enabled)
{
- bool partial = token[^1] == '*';
- if (partial)
- {
- token = token[..^1];
- }
+ loopbackNetworks.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo"));
+ }
- foreach ((string interfc, int interfcIndex) in _interfaceNames)
- {
- if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase))
- || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture)))
- {
- index ??= new List<int>();
- index.Add(interfcIndex);
- }
- }
+ if (IsIpv6Enabled)
+ {
+ loopbackNetworks.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo"));
}
- return index is not null;
+ return loopbackNetworks;
}
- /// <summary>
- /// Parses a string and adds it into the collection, replacing any interface references.
- /// </summary>
- /// <param name="col"><see cref="Collection{IPObject}"/>Collection.</param>
- /// <param name="token">String value to parse.</param>
- private void AddToCollection(Collection<IPObject> col, string token)
+ /// <inheritdoc/>
+ public IReadOnlyList<IPData> GetAllBindInterfaces(bool individualInterfaces = false)
{
- // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
- // Null check required here for automated testing.
- if (TryGetInterfaces(token, out var indices))
+ if (_interfaces.Count == 0)
{
- _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token);
+ // No bind address and no exclusions, so listen on all interfaces.
+ var result = new List<IPData>();
- // Replace all the interface tags with the interface IP's.
- foreach (IPNetAddress iface in _interfaceAddresses)
+ if (individualInterfaces)
{
- if (indices.Contains(Math.Abs(iface.Tag))
- && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
- || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
+ foreach (var iface in _interfaces)
{
- col.AddItem(iface);
+ result.Add(iface);
}
+
+ return result;
}
- }
- 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))
+
+ if (IsIpv4Enabled && IsIpv6Enabled)
{
- foreach (IPNetAddress iface in _interfaceAddresses)
- {
- if (obj.AddressFamily == iface.AddressFamily)
- {
- col.AddItem(iface);
- }
- }
+ // 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 (!IsIP6Enabled)
+ else if (IsIpv4Enabled)
{
- // Remove IP6 addresses from multi-homed IPHosts.
- obj.Remove(AddressFamily.InterNetworkV6);
- if (!obj.IsIP6())
- {
- col.AddItem(obj);
- }
+ result.Add(new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0)));
}
- else if (!IsIP4Enabled)
+ else if (IsIpv6Enabled)
{
- // Remove IP4 addresses from multi-homed IPHosts.
- obj.Remove(AddressFamily.InterNetwork);
- if (obj.IsIP6())
+ // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too.
+ foreach (var iface in _interfaces)
{
- col.AddItem(obj);
+ if (iface.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ result.Add(iface);
+ }
}
}
- else
- {
- col.AddItem(obj);
- }
- }
- else
- {
- _logger.LogDebug("Invalid or unknown object {Token}.", token);
+
+ return result;
}
- }
- /// <summary>
- /// Handler for network change events.
- /// </summary>
- /// <param name="sender">Sender.</param>
- /// <param name="e">A <see cref="NetworkAvailabilityEventArgs"/> containing network availability information.</param>
- private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e)
- {
- _logger.LogDebug("Network availability changed.");
- OnNetworkChanged();
+ return _interfaces;
}
- /// <summary>
- /// Handler for network change events.
- /// </summary>
- /// <param name="sender">Sender.</param>
- /// <param name="e">An <see cref="EventArgs"/>.</param>
- private void OnNetworkAddressChanged(object? sender, EventArgs e)
+ /// <inheritdoc/>
+ public string GetBindInterface(string source, out int? port)
{
- _logger.LogDebug("Network address change detected.");
- OnNetworkChanged();
+ _ = NetworkExtensions.TryParseHost(source, out var address, IsIpv4Enabled, IsIpv6Enabled);
+ var result = GetBindAddress(address.FirstOrDefault(), out port);
+ return result;
}
- /// <summary>
- /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession.
- /// </summary>
- /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
- private async Task OnNetworkChangeAsync()
+ /// <inheritdoc/>
+ public string GetBindInterface(HttpRequest source, out int? port)
{
- try
- {
- await Task.Delay(2000).ConfigureAwait(false);
- InitialiseInterfaces();
- // Recalculate LAN caches.
- InitialiseLAN(_configurationManager.GetNetworkConfiguration());
+ string result;
+ _ = NetworkExtensions.TryParseHost(source.Host.Host, out var addresses, IsIpv4Enabled, IsIpv6Enabled);
+ result = GetBindAddress(addresses.FirstOrDefault(), out port);
+ port ??= source.Host.Port;
- NetworkChanged?.Invoke(this, EventArgs.Empty);
- }
- finally
- {
- _eventfire = false;
- }
+ return result;
}
- /// <summary>
- /// Triggers our event, and re-loads interface information.
- /// </summary>
- private void OnNetworkChanged()
+ /// <inheritdoc/>
+ public string GetBindAddress(IPAddress? source, out int? port)
{
- lock (_eventFireLock)
+ port = null;
+
+ string result;
+
+ if (source != null)
{
- if (!_eventfire)
+ if (IsIpv4Enabled && !IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6)
{
- _logger.LogDebug("Network Address Change Event.");
- // As network events tend to fire one after the other only fire once every second.
- _eventfire = true;
- OnNetworkChangeAsync().GetAwaiter().GetResult();
+ _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
}
- }
- }
- /// <summary>
- /// Parses the user defined overrides into the dictionary object.
- /// Overrides are the equivalent of localised publishedServerUrl, enabling
- /// different addresses to be advertised over different subnets.
- /// format is subnet=ipaddress|host|uri
- /// when subnet = 0.0.0.0, any external address matches.
- /// </summary>
- private void InitialiseOverrides(NetworkConfiguration config)
- {
- lock (_intLock)
- {
- _publishedServerUrls.Clear();
- string[] overrides = config.PublishedServerUriBySubnet;
- if (overrides is null)
+ if (!IsIpv4Enabled && IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetwork)
{
- return;
+ _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
}
- foreach (var entry in overrides)
+ bool isExternal = !_lanSubnets.Any(network => network.Contains(source));
+ _logger.LogDebug("Trying to get bind address for source {Source} - External: {IsExternal}", source, isExternal);
+
+ if (MatchesPublishedServerUrl(source, isExternal, out result))
{
- var parts = entry.Split('=');
- if (parts.Length != 2)
- {
- _logger.LogError("Unable to parse bind override: {Entry}", entry);
- }
- else
- {
- var replacement = parts[1].Trim();
- if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase))
- {
- _publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement;
- }
- else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase))
- {
- _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement;
- }
- else if (TryParseInterface(parts[0], out Collection<IPObject>? addresses) && addresses is not null)
- {
- foreach (IPNetAddress na in addresses)
- {
- _publishedServerUrls[na] = replacement;
- }
- }
- else if (IPNetAddress.TryParse(parts[0], out IPNetAddress result))
- {
- _publishedServerUrls[result] = replacement;
- }
- else
- {
- _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]);
- }
- }
+ return result;
}
- }
- }
- /// <summary>
- /// Initialises the network bind addresses.
- /// </summary>
- private void InitialiseBind(NetworkConfiguration config)
- {
- lock (_intLock)
- {
- string[] lanAddresses = config.LocalNetworkAddresses;
-
- // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded.
- if (config.IgnoreVirtualInterfaces)
+ // No preference given, so move on to bind addresses.
+ if (MatchesBindInterface(source, isExternal, out result))
{
- // each virtual interface name must be prepended with the exclusion symbol !
- var virtualInterfaceNames = config.VirtualInterfaceNames.Split(',').Select(p => "!" + p).ToArray();
- if (lanAddresses.Length > 0)
- {
- var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length];
- Array.Copy(lanAddresses, newList, lanAddresses.Length);
- Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length);
- lanAddresses = newList;
- }
- else
- {
- lanAddresses = virtualInterfaceNames;
- }
+ return result;
}
- // Read and parse bind addresses and exclusions, removing ones that don't exist.
- _bindAddresses = CreateIPCollection(lanAddresses).ThatAreContainedInNetworks(_interfaceAddresses);
- _bindExclusions = CreateIPCollection(lanAddresses, true).ThatAreContainedInNetworks(_interfaceAddresses);
- _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString());
- _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString());
+ if (isExternal && MatchesExternalInterface(source, out result))
+ {
+ return result;
+ }
}
- }
- /// <summary>
- /// Initialises the remote address values.
- /// </summary>
- private void InitialiseRemote(NetworkConfiguration config)
- {
- lock (_intLock)
- {
- RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter);
- }
- }
+ // 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 => IsInLocalNetwork(x.Address))
+ .ThenBy(x => x.Index);
- /// <summary>
- /// Initialises internal LAN cache settings.
- /// </summary>
- private void InitialiseLAN(NetworkConfiguration config)
- {
- lock (_intLock)
+ if (availableInterfaces.Any())
{
- _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)
+ if (source != null)
{
- _logger.LogDebug("Using LAN interface addresses as user provided no LAN details.");
- // Internal interfaces must be private and not excluded.
- _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i)));
-
- // Subnets are the same as the calculated internal interface.
- _lanSubnets = new Collection<IPObject>();
-
- if (IsIP6Enabled)
+ foreach (var intf in availableInterfaces)
{
- _lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA
- _lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local
+ if (intf.Address.Equals(source))
+ {
+ result = NetworkExtensions.FormatIpString(intf.Address);
+ _logger.LogDebug("{Source}: Found matching interface to use as bind address: {Result}", source, result);
+ return result;
+ }
}
- if (IsIP4Enabled)
+ // 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)
{
- _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"));
+ if (intf.Subnet.Contains(source))
+ {
+ result = NetworkExtensions.FormatIpString(intf.Address);
+ _logger.LogDebug("{Source}: Found internal interface with matching subnet, using it as bind address: {Result}", source, result);
+ return result;
+ }
}
}
- 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());
+ result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address);
+ _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result);
+ return result;
}
+
+ // There isn't any others, so we'll use the loopback.
+ result = IsIpv4Enabled && !IsIpv6Enabled ? "127.0.0.1" : "::1";
+ _logger.LogWarning("{Source}: Only loopback {Result} returned, using that as bind address.", source, result);
+ return result;
}
- /// <summary>
- /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state.
- /// Generate a list of all active mac addresses that aren't loopback addresses.
- /// </summary>
- private void InitialiseInterfaces()
+ /// <inheritdoc/>
+ public IReadOnlyList<IPData> GetInternalBindAddresses()
{
- lock (_intLock)
- {
- _logger.LogDebug("Refreshing interfaces.");
+ // Select all local bind addresses
+ return _interfaces.Where(x => IsInLocalNetwork(x.Address))
+ .OrderBy(x => x.Index)
+ .ToList();
+ }
- _interfaceNames.Clear();
- _interfaceAddresses.Clear();
- _macAddresses.Clear();
+ /// <inheritdoc/>
+ public bool IsInLocalNetwork(string address)
+ {
+ if (NetworkExtensions.TryParseToSubnet(address, out var subnet))
+ {
+ return IPAddress.IsLoopback(subnet.Prefix) || (_lanSubnets.Any(x => x.Contains(subnet.Prefix)) && !_excludedSubnets.Any(x => x.Contains(subnet.Prefix)));
+ }
- try
+ if (NetworkExtensions.TryParseHost(address, out var addresses, IsIpv4Enabled, IsIpv6Enabled))
+ {
+ bool match = false;
+ foreach (var ept in addresses)
{
- IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces()
- .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up);
+ match |= IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept)));
+ }
- foreach (NetworkInterface adapter in nics)
- {
- try
- {
- IPInterfaceProperties ipProperties = adapter.GetIPProperties();
- PhysicalAddress mac = adapter.GetPhysicalAddress();
+ return match;
+ }
- // populate mac list
- if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac is not null && mac != PhysicalAddress.None)
- {
- _macAddresses.Add(mac);
- }
+ return false;
+ }
- // populate interface address list
- foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses)
- {
- if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork)
- {
- IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask))
- {
- // Keep the number of gateways on this interface, along with its index.
- Tag = ipProperties.GetIPv4Properties().Index
- };
-
- int tag = nw.Tag;
- if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback())
- {
- // -ve Tags signify the interface has a gateway.
- nw.Tag *= -1;
- }
-
- _interfaceAddresses.AddItem(nw, false);
-
- // Store interface name so we can use the name in Collections.
- _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
- _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
- }
- else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6)
- {
- IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength)
- {
- // Keep the number of gateways on this interface, along with its index.
- Tag = ipProperties.GetIPv6Properties().Index
- };
-
- int tag = nw.Tag;
- if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback())
- {
- // -ve Tags signify the interface has a gateway.
- nw.Tag *= -1;
- }
-
- _interfaceAddresses.AddItem(nw, false);
-
- // Store interface name so we can use the name in Collections.
- _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
- _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
- }
- }
- }
-#pragma warning disable CA1031 // Do not catch general exception types
- catch (Exception ex)
- {
- // Ignore error, and attempt to continue.
- _logger.LogError(ex, "Error encountered parsing interfaces.");
- }
-#pragma warning restore CA1031 // Do not catch general exception types
- }
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error in InitialiseInterfaces.");
- }
+ /// <inheritdoc/>
+ public bool IsInLocalNetwork(IPAddress address)
+ {
+ ArgumentNullException.ThrowIfNull(address);
- // If for some reason we don't have an interface info, resolve our DNS name.
- if (_interfaceAddresses.Count == 0)
- {
- _logger.LogError("No interfaces information available. Resolving DNS name.");
- IPHost host = new IPHost(Dns.GetHostName());
- foreach (var a in host.GetAddresses())
- {
- _interfaceAddresses.AddItem(a);
- }
+ // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
+ if (TrustAllIpv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ return true;
+ }
- if (_interfaceAddresses.Count == 0)
- {
- _logger.LogWarning("No interfaces information available. Using loopback.");
- }
- }
+ // As private addresses can be redefined by Configuration.LocalNetworkAddresses
+ var match = CheckIfLanAndNotExcluded(address);
- if (IsIP4Enabled)
- {
- _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback);
- }
+ return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback) || match;
+ }
- if (IsIP6Enabled)
- {
- _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback);
- }
+ private bool CheckIfLanAndNotExcluded(IPAddress address)
+ {
+ bool match = false;
+ foreach (var lanSubnet in _lanSubnets)
+ {
+ match |= lanSubnet.Contains(address);
+ }
- _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count);
- _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses.AsString());
+ foreach (var excludedSubnet in _excludedSubnets)
+ {
+ match &= !excludedSubnet.Contains(address);
}
+
+ NetworkExtensions.IsIPv6LinkLocal(address);
+ return match;
}
/// <summary>
- /// Attempts to match the source against a user defined bind interface.
+ /// Attempts to match the source against the published server URL overrides.
/// </summary>
/// <param name="source">IP source address to use.</param>
- /// <param name="isInExternalSubnet">True if the source is in the external subnet.</param>
- /// <param name="bindPreference">The published server url that matches the source address.</param>
- /// <param name="port">The resultant port, if one exists.</param>
+ /// <param name="isInExternalSubnet">True if the source is in an external subnet.</param>
+ /// <param name="bindPreference">The published server URL that matches the source address.</param>
/// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
- private bool MatchesPublishedServerUrl(IPObject source, bool isInExternalSubnet, out string bindPreference, out int? port)
+ private bool MatchesPublishedServerUrl(IPAddress source, bool isInExternalSubnet, out string bindPreference)
{
bindPreference = string.Empty;
- port = null;
+ int? port = null;
+
+ var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any)
+ || x.Key.Address.Equals(IPAddress.IPv6Any)
+ || x.Key.Subnet.Contains(source))
+ .GroupBy(x => x.Key)
+ .Select(x => x.First())
+ .OrderBy(x => x.Key.Address.Equals(IPAddress.Any)
+ || x.Key.Address.Equals(IPAddress.IPv6Any))
+ .ToList();
// Check for user override.
- foreach (var addr in _publishedServerUrls)
+ foreach (var data in validPublishedServerUrls)
{
- // Remaining. Match anything.
- if (addr.Key.Address.Equals(IPAddress.Broadcast))
- {
- bindPreference = addr.Value;
- break;
- }
- else if ((addr.Key.Address.Equals(IPAddress.Any) || addr.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet)
+ // Get address interface.
+ var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(x => data.Key.Subnet.Contains(x.Address));
+
+ if (isInExternalSubnet && (data.Key.Address.Equals(IPAddress.Any) || data.Key.Address.Equals(IPAddress.IPv6Any)))
{
// External.
- bindPreference = addr.Value;
+ bindPreference = data.Value;
break;
}
- else if (addr.Key.Contains(source))
+
+ if (intf?.Address != null)
{
- // Match ip address.
- bindPreference = addr.Value;
+ // Match IP address.
+ bindPreference = data.Value;
break;
}
}
if (string.IsNullOrEmpty(bindPreference))
{
+ _logger.LogDebug("{Source}: No matching bind address override found.", source);
return false;
}
@@ -1201,129 +910,121 @@ namespace Jellyfin.Networking.Manager
}
}
+ if (port != null)
+ {
+ _logger.LogDebug("{Source}: Matching bind address override found: {Address}:{Port}", source, bindPreference, port);
+ }
+ else
+ {
+ _logger.LogDebug("{Source}: Matching bind address override found: {Address}", source, bindPreference);
+ }
+
return true;
}
/// <summary>
- /// Attempts to match the source against a user defined bind interface.
+ /// Attempts to match the source against the user defined bind interfaces.
/// </summary>
/// <param name="source">IP source address to use.</param>
/// <param name="isInExternalSubnet">True if the source is in the external subnet.</param>
/// <param name="result">The result, if a match is found.</param>
/// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
- private bool MatchesBindInterface(IPObject source, bool isInExternalSubnet, out string result)
+ private bool MatchesBindInterface(IPAddress source, bool isInExternalSubnet, out string result)
{
result = string.Empty;
- var addresses = _bindAddresses.Exclude(_bindExclusions, false);
- int count = addresses.Count;
- if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any)))
+ int count = _interfaces.Count;
+ if (count == 1 && (_interfaces[0].Equals(IPAddress.Any) || _interfaces[0].Equals(IPAddress.IPv6Any)))
{
// Ignore IPAny addresses.
count = 0;
}
- if (count != 0)
+ if (count > 0)
{
- // Check to see if any of the bind interfaces are in the same subnet.
-
- IPAddress? defaultGateway = null;
IPAddress? bindAddress = null;
+ var externalInterfaces = _interfaces.Where(x => !IsInLocalNetwork(x.Address))
+ .OrderBy(x => x.Index)
+ .ToList();
if (isInExternalSubnet)
{
- // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first.
- foreach (var addr in addresses.OrderBy(p => p.Tag))
+ if (externalInterfaces.Any())
{
- if (defaultGateway is null && !IsInLocalNetwork(addr))
+ // Check to see if any of the external bind interfaces are in the same subnet as the source.
+ // If none exists, this will select the first external interface if there is one.
+ bindAddress = externalInterfaces
+ .OrderByDescending(x => x.Subnet.Contains(source))
+ .ThenBy(x => x.Index)
+ .Select(x => x.Address)
+ .FirstOrDefault();
+
+ if (bindAddress != null)
{
- defaultGateway = addr.Address;
- }
-
- if (bindAddress is null && addr.Contains(source))
- {
- bindAddress = addr.Address;
- }
-
- if (defaultGateway is not null && bindAddress is not null)
- {
- break;
+ result = NetworkExtensions.FormatIpString(bindAddress);
+ _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result);
+ return true;
}
}
- }
- 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;
- }
- if (bindAddress is not null)
- {
- result = FormatIP6String(bindAddress);
- _logger.LogDebug("{Source}: GetBindInterface: Has source, found a match bind interface subnets. {Result}", source, result);
- return true;
- }
-
- if (isInExternalSubnet && defaultGateway is not null)
- {
- result = FormatIP6String(defaultGateway);
- _logger.LogDebug("{Source}: GetBindInterface: Using first user defined external interface. {Result}", source, result);
- return true;
+ _logger.LogWarning("{Source}: External request received, no matching external bind address found, trying internal addresses.", source);
}
-
- result = FormatIP6String(addresses[0].Address);
- _logger.LogDebug("{Source}: GetBindInterface: Selected first user defined interface. {Result}", source, result);
-
- if (isInExternalSubnet)
+ else
{
- _logger.LogWarning("{Source}: External request received, however, only an internal interface bind found.", source);
+ // Check to see if any of the internal bind interfaces are in the same subnet as the source.
+ // If none exists, this will select the first internal interface if there is one.
+ bindAddress = _interfaces.Where(x => IsInLocalNetwork(x.Address))
+ .OrderByDescending(x => x.Subnet.Contains(source))
+ .ThenBy(x => x.Index)
+ .Select(x => x.Address)
+ .FirstOrDefault();
+
+ if (bindAddress != null)
+ {
+ result = NetworkExtensions.FormatIpString(bindAddress);
+ _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result);
+ return true;
+ }
}
-
- return true;
}
return false;
}
/// <summary>
- /// Attempts to match the source against an external interface.
+ /// Attempts to match the source against external interfaces.
/// </summary>
/// <param name="source">IP source address to use.</param>
/// <param name="result">The result, if a match is found.</param>
/// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
- private bool MatchesExternalInterface(IPObject source, out string result)
+ private bool MatchesExternalInterface(IPAddress source, out string result)
{
result = string.Empty;
// Get the first WAN interface address that isn't a loopback.
- var extResult = _interfaceAddresses
- .Exclude(_bindExclusions, false)
- .Where(p => !IsInLocalNetwork(p))
- .OrderBy(p => p.Tag)
- .ToList();
+ var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address)).OrderBy(x => x.Index);
- 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}: Found external interface with matching subnet, using it as bind address: {Result}", source, result);
+ return true;
}
+ }
- result = FormatIP6String(extResult.First().Address);
- _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface. {Result}", source, result);
+ if (hasResult != null)
+ {
+ result = NetworkExtensions.FormatIpString(hasResult);
+ _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result);
return true;
}
- _logger.LogDebug("{Source}: External request received, but no WAN interface found. Need to route through internal network.", source);
+ _logger.LogWarning("{Source}: External request received, but no external interface found. Need to route through internal network.", source);
return false;
}
}
diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
index e9af1cf83..5065fbdbb 100644
--- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
+++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
@@ -182,7 +182,7 @@ namespace Jellyfin.Server.Extensions
}
/// <summary>
- /// Extension method for adding the jellyfin API to the service collection.
+ /// Extension method for adding the Jellyfin API to the service collection.
/// </summary>
/// <param name="serviceCollection">The service collection.</param>
/// <param name="pluginAssemblies">An IEnumerable containing all plugin assemblies with API controllers.</param>
@@ -335,7 +335,7 @@ namespace Jellyfin.Server.Extensions
}
/// <summary>
- /// Sets up the proxy configuration based on the addresses in <paramref name="allowedProxies"/>.
+ /// Sets up the proxy configuration based on the addresses/subnets in <paramref name="allowedProxies"/>.
/// </summary>
/// <param name="config">The <see cref="NetworkConfiguration"/> containing the config settings.</param>
/// <param name="allowedProxies">The string array to parse.</param>
@@ -344,13 +344,20 @@ 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.TryParseToSubnet(allowedProxies[i], out var subnet))
{
- foreach (var address in host.GetAddresses())
+ if (subnet != null)
+ {
+ AddIpAddress(config, options, subnet.Prefix, subnet.PrefixLength);
+ }
+ }
+ else if (NetworkExtensions.TryParseHost(allowedProxies[i], out var addresses))
+ {
+ foreach (var address in addresses)
{
AddIpAddress(config, options, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128);
}
@@ -365,12 +372,9 @@ namespace Jellyfin.Server.Extensions
return;
}
- // In order for dual-mode sockets to be used, IP6 has to be enabled in JF and an interface has to have an IP6 address.
- if (addr.AddressFamily == AddressFamily.InterNetwork && config.EnableIPV6)
+ if (addr.IsIPv4MappedToIPv6)
{
- // If the server is using dual-mode sockets, IPv4 addresses are supplied in an IPv6 format.
- // https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-5.0 .
- addr = addr.MapToIPv6();
+ addr = addr.MapToIPv4();
}
if (prefixLength == 32)
diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs
index 5e601ca84..2c2715526 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; } = new string[] { "veth" };
public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>();
diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs
index b93939730..f0f16af78 100644
--- a/MediaBrowser.Common/Net/INetworkManager.cs
+++ b/MediaBrowser.Common/Net/INetworkManager.cs
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
-using System.Collections.ObjectModel;
using System.Net;
using System.Net.NetworkInformation;
using Microsoft.AspNetCore.Http;
@@ -18,47 +17,32 @@ namespace MediaBrowser.Common.Net
event EventHandler NetworkChanged;
/// <summary>
- /// Gets the published server urls list.
+ /// Gets a value indicating whether IPv4 is enabled.
/// </summary>
- Dictionary<IPNetAddress, string> PublishedServerUrls { get; }
+ bool IsIpv4Enabled { get; }
/// <summary>
- /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
+ /// Gets a value indicating whether IPv6 is enabled.
/// </summary>
- bool TrustAllIP6Interfaces { get; }
-
- /// <summary>
- /// Gets the remote address filter.
- /// </summary>
- Collection<IPObject> RemoteAddressFilter { get; }
-
- /// <summary>
- /// Gets or sets a value indicating whether iP6 is enabled.
- /// </summary>
- bool IsIP6Enabled { get; set; }
-
- /// <summary>
- /// Gets or sets a value indicating whether iP4 is enabled.
- /// </summary>
- bool IsIP4Enabled { get; set; }
+ bool IsIpv6Enabled { get; }
/// <summary>
/// Calculates the list of interfaces to use for Kestrel.
/// </summary>
- /// <returns>A Collection{IPObject} object containing all the interfaces to bind.
+ /// <returns>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.</returns>
/// <param name="individualInterfaces">When false, return <see cref="IPAddress.Any"/> or <see cref="IPAddress.IPv6Any"/> for all interfaces.</param>
- Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false);
+ IReadOnlyList<IPData> GetAllBindInterfaces(bool individualInterfaces = false);
/// <summary>
- /// Returns a collection containing the loopback interfaces.
+ /// Returns a list containing the loopback interfaces.
/// </summary>
- /// <returns>Collection{IPObject}.</returns>
- Collection<IPObject> GetLoopbacks();
+ /// <returns>List{IPData}.</returns>
+ IReadOnlyList<IPData> GetLoopbacks();
/// <summary>
- /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo)
/// If no bind addresses are specified, an internal interface address is selected.
/// The priority of selection is as follows:-
///
@@ -72,90 +56,50 @@ namespace MediaBrowser.Common.Net
///
/// If the source is from a public subnet address range and the user hasn't specified any bind addresses:-
/// The first public interface that isn't a loopback and contains the source subnet.
- /// The first public interface that isn't a loopback. Priority is given to interfaces with gateways.
- /// An internal interface if there are no public ip addresses.
+ /// The first public interface that isn't a loopback.
+ /// The first internal interface that isn't a loopback.
///
/// If the source is from a private subnet address range and the user hasn't specified any bind addresses:-
/// The first private interface that contains the source subnet.
- /// The first private interface that isn't a loopback. Priority is given to interfaces with gateways.
+ /// The first private interface that isn't a loopback.
///
/// If no interfaces meet any of these criteria, then a loopback address is returned.
///
- /// Interface that have been specifically excluded from binding are not used in any of the calculations.
- /// </summary>
- /// <param name="source">Source of the request.</param>
- /// <param name="port">Optional port returned, if it's part of an override.</param>
- /// <returns>IP Address to use, or loopback address if all else fails.</returns>
- string GetBindInterface(IPObject source, out int? port);
-
- /// <summary>
- /// 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 cref="GetBindInterface(IPObject, out int?)"/>.
+ /// Interfaces that have been specifically excluded from binding are not used in any of the calculations.
/// </summary>
/// <param name="source">Source of the request.</param>
/// <param name="port">Optional port returned, if it's part of an override.</param>
- /// <returns>IP Address to use, or loopback address if all else fails.</returns>
+ /// <returns>IP address to use, or loopback address if all else fails.</returns>
string GetBindInterface(HttpRequest source, out int? port);
/// <summary>
- /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo)
/// If no bind addresses are specified, an internal interface address is selected.
- /// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
+ /// (See <see cref="GetBindAddress(IPAddress, out int?)"/>.
/// </summary>
/// <param name="source">IP address of the request.</param>
/// <param name="port">Optional port returned, if it's part of an override.</param>
- /// <returns>IP Address to use, or loopback address if all else fails.</returns>
- string GetBindInterface(IPAddress source, out int? port);
+ /// <returns>IP address to use, or loopback address if all else fails.</returns>
+ string GetBindAddress(IPAddress source, out int? port);
/// <summary>
- /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo)
/// If no bind addresses are specified, an internal interface address is selected.
- /// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
+ /// (See <see cref="GetBindAddress(IPAddress, out int?)"/>.
/// </summary>
/// <param name="source">Source of the request.</param>
/// <param name="port">Optional port returned, if it's part of an override.</param>
- /// <returns>IP Address to use, or loopback address if all else fails.</returns>
+ /// <returns>IP address to use, or loopback address if all else fails.</returns>
string GetBindInterface(string source, out int? port);
/// <summary>
- /// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses.
- /// </summary>
- /// <param name="address">IP address to check.</param>
- /// <returns>True if it is.</returns>
- bool IsExcludedInterface(IPAddress address);
-
- /// <summary>
/// Get a list of all the MAC addresses associated with active interfaces.
/// </summary>
/// <returns>List of MAC addresses.</returns>
- IReadOnlyCollection<PhysicalAddress> GetMacAddresses();
-
- /// <summary>
- /// Checks to see if the IP Address provided matches an interface that has a gateway.
- /// </summary>
- /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
- /// <returns>Result of the check.</returns>
- bool IsGatewayInterface(IPObject? addressObj);
-
- /// <summary>
- /// Checks to see if the IP Address provided matches an interface that has a gateway.
- /// </summary>
- /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
- /// <returns>Result of the check.</returns>
- bool IsGatewayInterface(IPAddress? addressObj);
-
- /// <summary>
- /// Returns true if the address is a private address.
- /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
- /// </summary>
- /// <param name="address">Address to check.</param>
- /// <returns>True or False.</returns>
- bool IsPrivateAddressRange(IPObject address);
+ IReadOnlyList<PhysicalAddress> GetMacAddresses();
/// <summary>
/// Returns true if the address is part of the user defined LAN.
- /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
/// </summary>
/// <param name="address">IP to check.</param>
/// <returns>True if endpoint is within the LAN range.</returns>
@@ -163,76 +107,31 @@ namespace MediaBrowser.Common.Net
/// <summary>
/// Returns true if the address is part of the user defined LAN.
- /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
- /// </summary>
- /// <param name="address">IP to check.</param>
- /// <returns>True if endpoint is within the LAN range.</returns>
- bool IsInLocalNetwork(IPObject address);
-
- /// <summary>
- /// Returns true if the address is part of the user defined LAN.
- /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
/// </summary>
/// <param name="address">IP to check.</param>
/// <returns>True if endpoint is within the LAN range.</returns>
bool IsInLocalNetwork(IPAddress address);
/// <summary>
- /// 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".
/// </summary>
- /// <param name="token">Token to parse.</param>
- /// <param name="result">Resultant object's ip addresses, if successful.</param>
+ /// <param name="intf">Interface name.</param>
+ /// <param name="result">Resulting object's IP addresses, if successful.</param>
/// <returns>Success of the operation.</returns>
- bool TryParseInterface(string token, out Collection<IPObject>? result);
-
- /// <summary>
- /// Parses an array of strings into a Collection{IPObject}.
- /// </summary>
- /// <param name="values">Values to parse.</param>
- /// <param name="negated">When true, only include values beginning with !. When false, ignore ! values.</param>
- /// <returns>IPCollection object containing the value strings.</returns>
- Collection<IPObject> CreateIPCollection(string[] values, bool negated = false);
-
- /// <summary>
- /// Returns all the internal Bind interface addresses.
- /// </summary>
- /// <returns>An internal list of interfaces addresses.</returns>
- Collection<IPObject> GetInternalBindAddresses();
-
- /// <summary>
- /// Checks to see if an IP address is still a valid interface address.
- /// </summary>
- /// <param name="address">IP address to check.</param>
- /// <returns>True if it is.</returns>
- bool IsValidInterfaceAddress(IPAddress address);
-
- /// <summary>
- /// Returns true if the IP address is in the excluded list.
- /// </summary>
- /// <param name="ip">IP to check.</param>
- /// <returns>True if excluded.</returns>
- bool IsExcluded(IPAddress ip);
-
- /// <summary>
- /// Returns true if the IP address is in the excluded list.
- /// </summary>
- /// <param name="ip">IP to check.</param>
- /// <returns>True if excluded.</returns>
- bool IsExcluded(EndPoint ip);
+ bool TryParseInterface(string intf, out List<IPData>? result);
/// <summary>
- /// Gets the filtered LAN ip addresses.
+ /// Returns all internal (LAN) bind interface addresses.
/// </summary>
- /// <param name="filter">Optional filter for the list.</param>
- /// <returns>Returns a filtered list of LAN addresses.</returns>
- Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null);
+ /// <returns>An list of internal (LAN) interfaces addresses.</returns>
+ IReadOnlyList<IPData> GetInternalBindAddresses();
/// <summary>
- /// Checks to see if <paramref name="remoteIp"/> has access.
+ /// Checks if <paramref name="remoteIp"/> has access to the server.
/// </summary>
- /// <param name="remoteIp">IP Address of client.</param>
- /// <returns><b>True</b> if has access, otherwise <b>false</b>.</returns>
+ /// <param name="remoteIp">IP address of the client.</param>
+ /// <returns><b>True</b> if it has access, otherwise <b>false</b>.</returns>
bool HasRemoteAccess(IPAddress remoteIp);
}
}
diff --git a/MediaBrowser.Common/Net/IPData.cs b/MediaBrowser.Common/Net/IPData.cs
new file mode 100644
index 000000000..384efe8f6
--- /dev/null
+++ b/MediaBrowser.Common/Net/IPData.cs
@@ -0,0 +1,69 @@
+using System.Net;
+using System.Net.Sockets;
+using Microsoft.AspNetCore.HttpOverrides;
+
+namespace MediaBrowser.Common.Net
+{
+ /// <summary>
+ /// Base network object class.
+ /// </summary>
+ public class IPData
+ {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IPData"/> class.
+ /// </summary>
+ /// <param name="address">The <see cref="IPAddress"/>.</param>
+ /// <param name="subnet">The <see cref="IPNetwork"/>.</param>
+ /// <param name="name">The interface name.</param>
+ 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;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IPData"/> class.
+ /// </summary>
+ /// <param name="address">The <see cref="IPAddress"/>.</param>
+ /// <param name="subnet">The <see cref="IPNetwork"/>.</param>
+ public IPData(IPAddress address, IPNetwork? subnet)
+ : this(address, subnet, string.Empty)
+ {
+ }
+
+ /// <summary>
+ /// Gets or sets the object's IP address.
+ /// </summary>
+ public IPAddress Address { get; set; }
+
+ /// <summary>
+ /// Gets or sets the object's IP address.
+ /// </summary>
+ public IPNetwork Subnet { get; set; }
+
+ /// <summary>
+ /// Gets or sets the interface index.
+ /// </summary>
+ public int Index { get; set; }
+
+ /// <summary>
+ /// Gets or sets the interface name.
+ /// </summary>
+ public string Name { get; set; }
+
+ /// <summary>
+ /// Gets the AddressFamily of the object.
+ /// </summary>
+ 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 7cf1b8aa0..000000000
--- 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
-{
- /// <summary>
- /// Object that holds a host name.
- /// </summary>
- public class IPHost : IPObject
- {
- /// <summary>
- /// Gets or sets timeout value before resolve required, in minutes.
- /// </summary>
- public const int Timeout = 30;
-
- /// <summary>
- /// Represents an IPHost that has no value.
- /// </summary>
- public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None);
-
- /// <summary>
- /// Time when last resolved in ticks.
- /// </summary>
- private DateTime? _lastResolved = null;
-
- /// <summary>
- /// Gets the IP Addresses, attempting to resolve the name, if there are none.
- /// </summary>
- private IPAddress[] _addresses;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="IPHost"/> class.
- /// </summary>
- /// <param name="name">Host name to assign.</param>
- public IPHost(string name)
- {
- HostName = name ?? throw new ArgumentNullException(nameof(name));
- _addresses = Array.Empty<IPAddress>();
- Resolved = false;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="IPHost"/> class.
- /// </summary>
- /// <param name="name">Host name to assign.</param>
- /// <param name="address">Address to assign.</param>
- 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);
- }
-
- /// <summary>
- /// Gets or sets the object's first IP address.
- /// </summary>
- 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.");
- }
- }
-
- /// <summary>
- /// Gets or sets the object's first IP's subnet prefix.
- /// The setter does nothing, but shouldn't raise an exception.
- /// </summary>
- 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();
- }
-
- /// <summary>
- /// Gets a value indicating whether the address has a value.
- /// </summary>
- public bool HasAddress => _addresses.Length != 0;
-
- /// <summary>
- /// Gets the host name of this object.
- /// </summary>
- public string HostName { get; }
-
- /// <summary>
- /// Gets a value indicating whether this host has attempted to be resolved.
- /// </summary>
- public bool Resolved { get; private set; }
-
- /// <summary>
- /// Gets or sets the IP Addresses associated with this object.
- /// </summary>
- /// <param name="index">Index of address.</param>
- public IPAddress this[int index]
- {
- get
- {
- ResolveHost();
- return index >= 0 && index < _addresses.Length ? _addresses[index] : IPAddress.None;
- }
- }
-
- /// <summary>
- /// Attempts to parse the host string.
- /// </summary>
- /// <param name="host">Host name to parse.</param>
- /// <param name="hostObj">Object representing the string, if it has successfully been parsed.</param>
- /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns>
- 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;
- }
-
- /// <summary>
- /// Attempts to parse the host string.
- /// </summary>
- /// <param name="host">Host name to parse.</param>
- /// <returns>Object representing the string, if it has successfully been parsed.</returns>
- 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}");
- }
-
- /// <summary>
- /// Attempts to parse the host string, ensuring that it resolves only to a specific IP type.
- /// </summary>
- /// <param name="host">Host name to parse.</param>
- /// <param name="family">Addressfamily filter.</param>
- /// <returns>Object representing the string, if it has successfully been parsed.</returns>
- 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}");
- }
-
- /// <summary>
- /// Returns the Addresses that this item resolved to.
- /// </summary>
- /// <returns>IPAddress Array.</returns>
- public IPAddress[] GetAddresses()
- {
- ResolveHost();
- return _addresses;
- }
-
- /// <inheritdoc/>
- public override bool Contains(IPAddress address)
- {
- if (address is not null && !Address.Equals(IPAddress.None))
- {
- if (address.IsIPv4MappedToIPv6)
- {
- address = address.MapToIPv4();
- }
-
- foreach (var addr in GetAddresses())
- {
- if (address.Equals(addr))
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /// <inheritdoc/>
- 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;
- }
-
- /// <inheritdoc/>
- 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;
- }
-
- /// <inheritdoc/>
- 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;
- }
-
- /// <inheritdoc/>
- public override void Remove(AddressFamily family)
- {
- if (ResolveHost())
- {
- _addresses = _addresses.Where(p => p.AddressFamily != family).ToArray();
- }
- }
-
- /// <inheritdoc/>
- public override bool Contains(IPObject address)
- {
- // An IPHost cannot contain another IPObject, it can only be equal.
- return Equals(address);
- }
-
- /// <inheritdoc/>
- protected override IPObject CalculateNetworkAddress()
- {
- var (address, prefixLength) = NetworkAddressOf(this[0], PrefixLength);
- return new IPNetAddress(address, prefixLength);
- }
-
- /// <summary>
- /// Attempt to resolve the ip address of a host.
- /// </summary>
- /// <returns><c>true</c> if any addresses have been resolved, otherwise <c>false</c>.</returns>
- 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;
- }
-
- /// <summary>
- /// Task that looks up a Host name and returns its IP addresses.
- /// </summary>
- 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 ac3396a9f..000000000
--- a/MediaBrowser.Common/Net/IPNetAddress.cs
+++ /dev/null
@@ -1,273 +0,0 @@
-using System;
-using System.Net;
-using System.Net.Sockets;
-
-namespace MediaBrowser.Common.Net
-{
- /// <summary>
- /// An object that holds and IP address and subnet mask.
- /// </summary>
- public class IPNetAddress : IPObject
- {
- /// <summary>
- /// Represents an IPNetAddress that has no value.
- /// </summary>
- public static readonly IPNetAddress None = new IPNetAddress(IPAddress.None);
-
- /// <summary>
- /// IPv4 multicast address.
- /// </summary>
- public static readonly IPAddress SSDPMulticastIPv4 = IPAddress.Parse("239.255.255.250");
-
- /// <summary>
- /// IPv6 local link multicast address.
- /// </summary>
- public static readonly IPAddress SSDPMulticastIPv6LinkLocal = IPAddress.Parse("ff02::C");
-
- /// <summary>
- /// IPv6 site local multicast address.
- /// </summary>
- public static readonly IPAddress SSDPMulticastIPv6SiteLocal = IPAddress.Parse("ff05::C");
-
- /// <summary>
- /// IP4Loopback address host.
- /// </summary>
- public static readonly IPNetAddress IP4Loopback = IPNetAddress.Parse("127.0.0.1/8");
-
- /// <summary>
- /// IP6Loopback address host.
- /// </summary>
- public static readonly IPNetAddress IP6Loopback = new IPNetAddress(IPAddress.IPv6Loopback);
-
- /// <summary>
- /// Object's IP address.
- /// </summary>
- private IPAddress _address;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="IPNetAddress"/> class.
- /// </summary>
- /// <param name="address">Address to assign.</param>
- public IPNetAddress(IPAddress address)
- {
- _address = address ?? throw new ArgumentNullException(nameof(address));
- PrefixLength = (byte)(address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128);
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="IPNetAddress"/> class.
- /// </summary>
- /// <param name="address">IP Address.</param>
- /// <param name="prefixLength">Mask as a CIDR.</param>
- public IPNetAddress(IPAddress address, byte prefixLength)
- {
- if (address?.IsIPv4MappedToIPv6 ?? throw new ArgumentNullException(nameof(address)))
- {
- _address = address.MapToIPv4();
- }
- else
- {
- _address = address;
- }
-
- PrefixLength = prefixLength;
- }
-
- /// <summary>
- /// Gets or sets the object's IP address.
- /// </summary>
- public override IPAddress Address
- {
- get
- {
- return _address;
- }
-
- set
- {
- _address = value ?? IPAddress.None;
- }
- }
-
- /// <inheritdoc/>
- public override byte PrefixLength { get; set; }
-
- /// <summary>
- /// Try to parse the address and subnet strings into an IPNetAddress object.
- /// </summary>
- /// <param name="addr">IP address to parse. Can be CIDR or X.X.X.X notation.</param>
- /// <param name="ip">Resultant object.</param>
- /// <returns>True if the values parsed successfully. False if not, resulting in the IP being null.</returns>
- 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;
- }
-
- /// <summary>
- /// Parses the string provided, throwing an exception if it is badly formed.
- /// </summary>
- /// <param name="addr">String to parse.</param>
- /// <returns>IPNetAddress object.</returns>
- public static IPNetAddress Parse(string addr)
- {
- if (TryParse(addr, out IPNetAddress o))
- {
- return o;
- }
-
- throw new ArgumentException("Unable to recognise object :" + addr);
- }
-
- /// <inheritdoc/>
- public override bool Contains(IPAddress address)
- {
- ArgumentNullException.ThrowIfNull(address);
-
- if (address.IsIPv4MappedToIPv6)
- {
- address = address.MapToIPv4();
- }
-
- var (altAddress, altPrefix) = NetworkAddressOf(address, PrefixLength);
- return NetworkAddress.Address.Equals(altAddress) && NetworkAddress.PrefixLength >= altPrefix;
- }
-
- /// <inheritdoc/>
- 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;
- }
-
- /// <inheritdoc/>
- 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;
- }
-
- /// <inheritdoc/>
- public override bool Equals(IPAddress ip)
- {
- if (ip is not null && !ip.Equals(IPAddress.None) && !Address.Equals(IPAddress.None))
- {
- return ip.Equals(Address);
- }
-
- return false;
- }
-
- /// <inheritdoc/>
- public override string ToString()
- {
- return ToString(false);
- }
-
- /// <summary>
- /// Returns a textual representation of this object.
- /// </summary>
- /// <param name="shortVersion">Set to true, if the subnet is to be excluded as part of the address.</param>
- /// <returns>String representation of this object.</returns>
- 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;
- }
-
- /// <inheritdoc/>
- 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 93655234b..000000000
--- a/MediaBrowser.Common/Net/IPObject.cs
+++ /dev/null
@@ -1,355 +0,0 @@
-using System;
-using System.Net;
-using System.Net.Sockets;
-
-namespace MediaBrowser.Common.Net
-{
- /// <summary>
- /// Base network object class.
- /// </summary>
- public abstract class IPObject : IEquatable<IPObject>
- {
- /// <summary>
- /// The network address of this object.
- /// </summary>
- private IPObject? _networkAddress;
-
- /// <summary>
- /// Gets or sets a user defined value that is associated with this object.
- /// </summary>
- public int Tag { get; set; }
-
- /// <summary>
- /// Gets or sets the object's IP address.
- /// </summary>
- public abstract IPAddress Address { get; set; }
-
- /// <summary>
- /// Gets the object's network address.
- /// </summary>
- public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress();
-
- /// <summary>
- /// Gets or sets the object's IP address.
- /// </summary>
- public abstract byte PrefixLength { get; set; }
-
- /// <summary>
- /// Gets the AddressFamily of this object.
- /// </summary>
- 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;
- }
- }
-
- /// <summary>
- /// Returns the network address of an object.
- /// </summary>
- /// <param name="address">IP Address to convert.</param>
- /// <param name="prefixLength">Subnet prefix.</param>
- /// <returns>IPAddress.</returns>
- public static (IPAddress Address, byte PrefixLength) NetworkAddressOf(IPAddress address, byte prefixLength)
- {
- ArgumentNullException.ThrowIfNull(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<byte> 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);
- }
-
- /// <summary>
- /// Tests to see if the ip address is an IP6 address.
- /// </summary>
- /// <param name="address">Value to test.</param>
- /// <returns>True if it is.</returns>
- public static bool IsIP6(IPAddress address)
- {
- ArgumentNullException.ThrowIfNull(address);
-
- if (address.IsIPv4MappedToIPv6)
- {
- address = address.MapToIPv4();
- }
-
- return !address.Equals(IPAddress.None) && (address.AddressFamily == AddressFamily.InterNetworkV6);
- }
-
- /// <summary>
- /// Tests to see if the address in the private address range.
- /// </summary>
- /// <param name="address">Object to test.</param>
- /// <returns>True if it contains a private address.</returns>
- public static bool IsPrivateAddressRange(IPAddress address)
- {
- ArgumentNullException.ThrowIfNull(address);
-
- if (!address.Equals(IPAddress.None))
- {
- if (address.IsIPv4MappedToIPv6)
- {
- address = address.MapToIPv4();
- }
-
- if (address.AddressFamily == AddressFamily.InterNetwork)
- {
- // GetAddressBytes
- Span<byte> 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<byte> octet = stackalloc byte[16];
- address.TryWriteBytes(octet, out _);
-
- uint word = (uint)(octet[0] << 8) + octet[1];
-
- return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link.
- || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address.
- }
- }
-
- return false;
- }
-
- /// <summary>
- /// Returns true if the IPAddress contains an IP6 Local link address.
- /// </summary>
- /// <param name="address">IPAddress object to check.</param>
- /// <returns>True if it is a local link address.</returns>
- /// <remarks>
- /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress
- /// it appears that the IPAddress.IsIPv6LinkLocal is out of date.
- /// </remarks>
- public static bool IsIPv6LinkLocal(IPAddress address)
- {
- ArgumentNullException.ThrowIfNull(address);
-
- if (address.IsIPv4MappedToIPv6)
- {
- address = address.MapToIPv4();
- }
-
- if (address.AddressFamily != AddressFamily.InterNetworkV6)
- {
- return false;
- }
-
- // GetAddressBytes
- Span<byte> octet = stackalloc byte[16];
- address.TryWriteBytes(octet, out _);
- uint word = (uint)(octet[0] << 8) + octet[1];
-
- return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link.
- }
-
- /// <summary>
- /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
- /// </summary>
- /// <param name="cidr">Subnet mask in CIDR notation.</param>
- /// <param name="family">IPv4 or IPv6 family.</param>
- /// <returns>String value of the subnet mask in dotted decimal notation.</returns>
- public static IPAddress CidrToMask(byte cidr, AddressFamily family)
- {
- uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr);
- addr = ((addr & 0xff000000) >> 24)
- | ((addr & 0x00ff0000) >> 8)
- | ((addr & 0x0000ff00) << 8)
- | ((addr & 0x000000ff) << 24);
- return new IPAddress(addr);
- }
-
- /// <summary>
- /// Convert a mask to a CIDR. IPv4 only.
- /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask.
- /// </summary>
- /// <param name="mask">Subnet mask.</param>
- /// <returns>Byte CIDR representing the mask.</returns>
- public static byte MaskToCidr(IPAddress mask)
- {
- ArgumentNullException.ThrowIfNull(mask);
-
- byte cidrnet = 0;
- if (!mask.Equals(IPAddress.Any))
- {
- // GetAddressBytes
- Span<byte> 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;
- }
-
- /// <summary>
- /// Tests to see if this object is a Loopback address.
- /// </summary>
- /// <returns>True if it is.</returns>
- public virtual bool IsLoopback()
- {
- return IPAddress.IsLoopback(Address);
- }
-
- /// <summary>
- /// Removes all addresses of a specific type from this object.
- /// </summary>
- /// <param name="family">Type of address to remove.</param>
- public virtual void Remove(AddressFamily family)
- {
- // This method only performs a function in the IPHost implementation of IPObject.
- }
-
- /// <summary>
- /// Tests to see if this object is an IPv6 address.
- /// </summary>
- /// <returns>True if it is.</returns>
- public virtual bool IsIP6()
- {
- return IsIP6(Address);
- }
-
- /// <summary>
- /// Returns true if this IP address is in the RFC private address range.
- /// </summary>
- /// <returns>True this object has a private address.</returns>
- public virtual bool IsPrivateAddressRange()
- {
- return IsPrivateAddressRange(Address);
- }
-
- /// <summary>
- /// Compares this to the object passed as a parameter.
- /// </summary>
- /// <param name="ip">Object to compare to.</param>
- /// <returns>Equality result.</returns>
- public virtual bool Equals(IPAddress ip)
- {
- if (ip is not null)
- {
- if (ip.IsIPv4MappedToIPv6)
- {
- ip = ip.MapToIPv4();
- }
-
- return !Address.Equals(IPAddress.None) && Address.Equals(ip);
- }
-
- return false;
- }
-
- /// <summary>
- /// Compares this to the object passed as a parameter.
- /// </summary>
- /// <param name="other">Object to compare to.</param>
- /// <returns>Equality result.</returns>
- public virtual bool Equals(IPObject? other)
- {
- if (other is not null)
- {
- return !Address.Equals(IPAddress.None) && Address.Equals(other.Address);
- }
-
- return false;
- }
-
- /// <summary>
- /// Compares the address in this object and the address in the object passed as a parameter.
- /// </summary>
- /// <param name="address">Object's IP address to compare to.</param>
- /// <returns>Comparison result.</returns>
- public abstract bool Contains(IPObject address);
-
- /// <summary>
- /// Compares the address in this object and the address in the object passed as a parameter.
- /// </summary>
- /// <param name="address">Object's IP address to compare to.</param>
- /// <returns>Comparison result.</returns>
- public abstract bool Contains(IPAddress address);
-
- /// <inheritdoc/>
- public override int GetHashCode()
- {
- return Address.GetHashCode();
- }
-
- /// <inheritdoc/>
- public override bool Equals(object? obj)
- {
- return Equals(obj as IPObject);
- }
-
- /// <summary>
- /// Calculates the network address of this object.
- /// </summary>
- /// <returns>Returns the network address of this object.</returns>
- protected abstract IPObject CalculateNetworkAddress();
- }
-}
diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs
index 5e5e5b81b..97f0abbb5 100644
--- a/MediaBrowser.Common/Net/NetworkExtensions.cs
+++ b/MediaBrowser.Common/Net/NetworkExtensions.cs
@@ -1,6 +1,10 @@
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;
+using Microsoft.AspNetCore.HttpOverrides;
namespace MediaBrowser.Common.Net
{
@@ -9,240 +13,351 @@ namespace MediaBrowser.Common.Net
/// </summary>
public static class NetworkExtensions
{
+ // Use regular expression as CheckHostName isn't RFC5892 compliant.
+ // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation
+ private static readonly Regex _fqdnRegex = new Regex(@"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$");
+
/// <summary>
- /// Add an address to the collection.
+ /// Returns true if the IPAddress contains an IP6 Local link address.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="ip">Item to add.</param>
- public static void AddItem(this Collection<IPObject> source, IPAddress ip)
+ /// <param name="address">IPAddress object to check.</param>
+ /// <returns>True if it is a local link address.</returns>
+ /// <remarks>
+ /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress
+ /// it appears that the IPAddress.IsIPv6LinkLocal is out of date.
+ /// </remarks>
+ public static bool IsIPv6LinkLocal(IPAddress address)
{
- if (!source.ContainsAddress(ip))
+ ArgumentNullException.ThrowIfNull(address);
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ if (address.AddressFamily != AddressFamily.InterNetworkV6)
{
- source.Add(new IPNetAddress(ip, 32));
+ return false;
}
+
+ // GetAddressBytes
+ Span<byte> octet = stackalloc byte[16];
+ address.TryWriteBytes(octet, out _);
+ uint word = (uint)(octet[0] << 8) + octet[1];
+
+ return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link.
}
/// <summary>
- /// Adds a network to the collection.
+ /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="item">Item to add.</param>
- /// <param name="itemsAreNetworks">If <c>true</c> the values are treated as subnets.
- /// If <b>false</b> items are addresses.</param>
- public static void AddItem(this Collection<IPObject> source, IPObject item, bool itemsAreNetworks = true)
+ /// <param name="cidr">Subnet mask in CIDR notation.</param>
+ /// <param name="family">IPv4 or IPv6 family.</param>
+ /// <returns>String value of the subnet mask in dotted decimal notation.</returns>
+ public static IPAddress CidrToMask(byte cidr, AddressFamily family)
{
- if (!source.ContainsAddress(item) || !itemsAreNetworks)
- {
- source.Add(item);
- }
+ 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);
}
/// <summary>
- /// Converts this object to a string.
+ /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <returns>Returns a string representation of this object.</returns>
- public static string AsString(this Collection<IPObject> source)
+ /// <param name="cidr">Subnet mask in CIDR notation.</param>
+ /// <param name="family">IPv4 or IPv6 family.</param>
+ /// <returns>String value of the subnet mask in dotted decimal notation.</returns>
+ public static IPAddress CidrToMask(int cidr, AddressFamily family)
{
- return $"[{string.Join(',', source)}]";
+ 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);
}
/// <summary>
- /// Returns true if the collection contains an item with the ip address,
- /// or the ip address falls within any of the collection's network ranges.
+ /// Convert a subnet mask to a CIDR. IPv4 only.
+ /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="item">The item to look for.</param>
- /// <returns>True if the collection contains the item.</returns>
- public static bool ContainsAddress(this Collection<IPObject> source, IPAddress item)
+ /// <param name="mask">Subnet mask.</param>
+ /// <returns>Byte CIDR representing the mask.</returns>
+ public static byte MaskToCidr(IPAddress mask)
{
- if (source.Count == 0)
- {
- return false;
- }
-
- ArgumentNullException.ThrowIfNull(item);
+ ArgumentNullException.ThrowIfNull(mask);
- if (item.IsIPv4MappedToIPv6)
+ byte cidrnet = 0;
+ if (!mask.Equals(IPAddress.Any))
{
- item = item.MapToIPv4();
- }
+ // GetAddressBytes
+ Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
+ mask.TryWriteBytes(bytes, out _);
- foreach (var i in source)
- {
- if (i.Contains(item))
+ var zeroed = false;
+ for (var i = 0; i < bytes.Length; i++)
{
- return true;
+ for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1)
+ {
+ if (zeroed)
+ {
+ // Invalid netmask.
+ return (byte)~cidrnet;
+ }
+
+ if ((v & 0x80) == 0)
+ {
+ zeroed = true;
+ }
+ else
+ {
+ cidrnet++;
+ }
+ }
}
}
- return false;
+ return cidrnet;
}
/// <summary>
- /// 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.
+ /// Converts an IPAddress into a string.
+ /// Ipv6 addresses are returned in [ ], with their scope removed.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="item">The item to look for.</param>
- /// <returns>True if the collection contains the item.</returns>
- public static bool ContainsAddress(this Collection<IPObject> source, IPObject item)
+ /// <param name="address">Address to convert.</param>
+ /// <returns>URI safe conversion of the address.</returns>
+ public static string FormatIpString(IPAddress? address)
{
- if (source.Count == 0)
+ if (address is null)
{
- return false;
+ return string.Empty;
}
- ArgumentNullException.ThrowIfNull(item);
-
- foreach (var i in source)
+ var str = address.ToString();
+ if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
- if (i.Contains(item))
+ int i = str.IndexOf('%', StringComparison.Ordinal);
+ if (i != -1)
{
- return true;
+ str = str.Substring(0, i);
}
+
+ return $"[{str}]";
}
- return false;
+ return str;
}
/// <summary>
- /// Compares two Collection{IPObject} objects. The order is ignored.
+ /// Try parsing an array of strings into <see cref="IPNetwork"/> objects, respecting exclusions.
+ /// Elements without a subnet mask will be represented as <see cref="IPNetwork"/> with a single IP.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="dest">Item to compare to.</param>
- /// <returns>True if both are equal.</returns>
- public static bool Compare(this Collection<IPObject> source, Collection<IPObject> dest)
+ /// <param name="values">Input string array to be parsed.</param>
+ /// <param name="result">Collection of <see cref="IPNetwork"/>.</param>
+ /// <param name="negated">Boolean signaling if negated or not negated values should be parsed.</param>
+ /// <returns><c>True</c> if parsing was successful.</returns>
+ public static bool TryParseToSubnets(string[] values, out List<IPNetwork> result, bool negated = false)
{
- if (dest is null || source.Count != dest.Count)
+ result = new List<IPNetwork>();
+
+ if (values is null || values.Length == 0)
{
return false;
}
- foreach (var sourceItem in source)
+ for (int a = 0; a < values.Length; a++)
{
- bool found = false;
- foreach (var destItem in dest)
+ string[] v = values[a].Trim().Split("/");
+
+ var address = IPAddress.None;
+ if (negated && v[0].StartsWith('!'))
{
- if (sourceItem.Equals(destItem))
- {
- found = true;
- break;
- }
+ _ = IPAddress.TryParse(v[0][1..], out address);
+ }
+ else if (!negated)
+ {
+ _ = IPAddress.TryParse(v[0][0..], out address);
}
- if (!found)
+ if (address != IPAddress.None && address is not null)
{
- return false;
+ if (v.Length > 1 && int.TryParse(v[1], out var netmask))
+ {
+ result.Add(new IPNetwork(address, netmask));
+ }
+ else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress))
+ {
+ result.Add(new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)));
+ }
+ else if (address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ result.Add(new IPNetwork(address, 32));
+ }
+ else if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ result.Add(new IPNetwork(address, 128));
+ }
}
}
- return true;
+ if (result.Count > 0)
+ {
+ return true;
+ }
+
+ return false;
}
/// <summary>
- /// Returns a collection containing the subnets of this collection given.
+ /// Try parsing a string into an <see cref="IPNetwork"/>, respecting exclusions.
+ /// Inputs without a subnet mask will be represented as <see cref="IPNetwork"/> with a single IP.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <returns>Collection{IPObject} object containing the subnets.</returns>
- public static Collection<IPObject> AsNetworks(this Collection<IPObject> source)
+ /// <param name="value">Input string to be parsed.</param>
+ /// <param name="result">An <see cref="IPNetwork"/>.</param>
+ /// <param name="negated">Boolean signaling if negated or not negated values should be parsed.</param>
+ /// <returns><c>True</c> if parsing was successful.</returns>
+ public static bool TryParseToSubnet(string value, out IPNetwork result, bool negated = false)
{
- ArgumentNullException.ThrowIfNull(source);
+ result = new IPNetwork(IPAddress.None, 32);
+
+ if (string.IsNullOrEmpty(value))
+ {
+ return false;
+ }
- Collection<IPObject> res = new Collection<IPObject>();
+ string[] v = value.Trim().Split("/");
+
+ var address = IPAddress.None;
+ if (negated && v[0].StartsWith('!'))
+ {
+ _ = IPAddress.TryParse(v[0][1..], out address);
+ }
+ else if (!negated)
+ {
+ _ = IPAddress.TryParse(v[0][0..], out address);
+ }
- foreach (IPObject i in source)
+ if (address != IPAddress.None && address is not null)
{
- if (i is IPNetAddress nw)
+ if (v.Length > 1 && int.TryParse(v[1], out var netmask))
{
- // Add the subnet calculated from the interface address/mask.
- var na = nw.NetworkAddress;
- na.Tag = i.Tag;
- res.AddItem(na);
+ result = new IPNetwork(address, netmask);
}
- else if (i is IPHost ipHost)
+ else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress))
{
- // Flatten out IPHost and add all its ip addresses.
- foreach (var addr in ipHost.GetAddresses())
- {
- IPNetAddress host = new IPNetAddress(addr)
- {
- Tag = i.Tag
- };
-
- res.AddItem(host);
- }
+ result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress));
}
+ else if (address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ result = new IPNetwork(address, 32);
+ }
+ else if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ result = new IPNetwork(address, 128);
+ }
+ }
+
+ if (!result.Prefix.Equals(IPAddress.None))
+ {
+ return true;
}
- return res;
+ return false;
}
/// <summary>
- /// Excludes all the items from this list that are found in excludeList.
+ /// Attempts to parse a host string.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="excludeList">Items to exclude.</param>
- /// <param name="isNetwork">Collection is a network collection.</param>
- /// <returns>A new collection, with the items excluded.</returns>
- public static Collection<IPObject> Exclude(this Collection<IPObject> source, Collection<IPObject> excludeList, bool isNetwork)
+ /// <param name="host">Host name to parse.</param>
+ /// <param name="addresses">Object representing the string, if it has successfully been parsed.</param>
+ /// <param name="isIpv4Enabled"><c>true</c> if IPv4 is enabled.</param>
+ /// <param name="isIpv6Enabled"><c>true</c> if IPv6 is enabled.</param>
+ /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns>
+ public static bool TryParseHost(string host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIpv4Enabled = true, bool isIpv6Enabled = false)
{
- if (source.Count == 0 || excludeList is null)
+ if (string.IsNullOrWhiteSpace(host))
{
- return new Collection<IPObject>(source);
+ addresses = Array.Empty<IPAddress>();
+ return false;
}
- Collection<IPObject> results = new Collection<IPObject>();
+ host = host.Trim();
- bool found;
- foreach (var outer in source)
+ // See if it's an IPv6 with port address e.g. [::1] or [::1]:120.
+ if (host[0] == '[')
{
- found = false;
+ int i = host.IndexOf(']', StringComparison.Ordinal);
+ if (i != -1)
+ {
+ return TryParseHost(host.Remove(i)[1..], out addresses);
+ }
+
+ addresses = Array.Empty<IPAddress>();
+ return false;
+ }
+
+ var hosts = host.Split(':');
- foreach (var inner in excludeList)
+ if (hosts.Length <= 2)
+ {
+ // Is hostname or hostname:port
+ if (_fqdnRegex.IsMatch(hosts[0]))
{
- if (outer.Equals(inner))
+ try
+ {
+ addresses = Dns.GetHostAddresses(hosts[0]);
+ return true;
+ }
+ catch (SocketException)
{
- found = true;
- break;
+ // Log and then ignore socket errors, as the result value will just be an empty array.
+ Console.WriteLine("GetHostAddresses failed.");
}
}
- if (!found)
+ // 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<IPAddress>();
+ return false;
+ }
+
+ addresses = new[] { address };
+
+ // Host name is an ip4 address, so fake resolve.
+ return true;
}
}
+ else if (hosts.Length <= 9 && IPAddress.TryParse(host.Split('/')[0], out var address)) // 8 octets + port
+ {
+ addresses = new[] { address };
+ return true;
+ }
- return results;
+ addresses = Array.Empty<IPAddress>();
+ return false;
}
/// <summary>
- /// Returns all items that co-exist in this object and target.
+ /// Gets the broadcast address for a <see cref="IPNetwork"/>.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="target">Collection to compare with.</param>
- /// <returns>A collection containing all the matches.</returns>
- public static Collection<IPObject> ThatAreContainedInNetworks(this Collection<IPObject> source, Collection<IPObject> target)
+ /// <param name="network">The <see cref="IPNetwork"/>.</param>
+ /// <returns>The broadcast address.</returns>
+ public static IPAddress GetBroadcastAddress(IPNetwork network)
{
- if (source.Count == 0)
- {
- return new Collection<IPObject>();
- }
-
- ArgumentNullException.ThrowIfNull(target);
-
- Collection<IPObject> nc = new Collection<IPObject>();
-
- foreach (IPObject i in source)
- {
- if (target.ContainsAddress(i))
- {
- nc.AddItem(i);
- }
- }
+ uint ipAddress = BitConverter.ToUInt32(network.Prefix.GetAddressBytes(), 0);
+ uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0);
+ uint broadCastIpAddress = ipAddress | ~ipMaskV4;
- return nc;
+ return new IPAddress(BitConverter.GetBytes(broadCastIpAddress));
}
}
}
diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs
index 11afdc4ae..45ac5c3a8 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
/// <summary>
/// Gets an URL that can be used to access the API over LAN.
/// </summary>
- /// <param name="hostname">An optional hostname to use.</param>
+ /// <param name="ipAddress">An optional IP address to use.</param>
/// <param name="allowHttps">A value indicating whether to allow HTTPS.</param>
/// <returns>The API URL.</returns>
- string GetApiUrlForLocalAccess(IPObject hostname = null, bool allowHttps = true);
+ string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true);
/// <summary>
/// Gets a local (LAN) URL that can be used to access the API.
diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs
index a2835b711..f3bc31796 100644
--- a/MediaBrowser.Model/Net/ISocketFactory.cs
+++ b/MediaBrowser.Model/Net/ISocketFactory.cs
@@ -23,9 +23,10 @@ namespace MediaBrowser.Model.Net
/// Creates a new multicast socket using the specified multicast IP address, multicast time to live and local port.
/// </summary>
/// <param name="ipAddress">The multicast IP address to bind to.</param>
+ /// <param name="bindIpAddress">The bind IP address.</param>
/// <param name="multicastTimeToLive">The multicast time to live value. Actually a maximum number of network hops for UDP packets.</param>
/// <param name="localPort">The local port to bind to.</param>
/// <returns>A <see cref="ISocket"/> implementation.</returns>
- ISocket CreateUdpMulticastSocket(IPAddress ipAddress, int multicastTimeToLive, int localPort);
+ ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress bindIpAddress, int multicastTimeToLive, int localPort);
}
}
diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs
index 6e4f5634d..da357546d 100644
--- a/RSSDP/SsdpCommunicationsServer.cs
+++ b/RSSDP/SsdpCommunicationsServer.cs
@@ -33,7 +33,7 @@ namespace Rssdp.Infrastructure
*/
private object _BroadcastListenSocketSynchroniser = new object();
- private ISocket _BroadcastListenSocket;
+ private List<ISocket> _BroadcastListenSockets;
private object _SendSocketSynchroniser = new object();
private List<ISocket> _sendSockets;
@@ -111,24 +111,21 @@ namespace Rssdp.Infrastructure
{
ThrowIfDisposed();
- if (_BroadcastListenSocket == null)
+ lock (_BroadcastListenSocketSynchroniser)
{
- lock (_BroadcastListenSocketSynchroniser)
+ if (_BroadcastListenSockets == null)
{
- if (_BroadcastListenSocket == null)
+ try
+ {
+ _BroadcastListenSockets = ListenForBroadcasts();
+ }
+ catch (SocketException ex)
+ {
+ _logger.LogError("Failed to bind to port 1900: {Message}. DLNA will be unavailable", ex.Message);
+ }
+ catch (Exception ex)
{
- try
- {
- _BroadcastListenSocket = ListenForBroadcastsAsync();
- }
- catch (SocketException ex)
- {
- _logger.LogError("Failed to bind to port 1900: {Message}. DLNA will be unavailable", ex.Message);
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error in BeginListeningForBroadcasts");
- }
+ _logger.LogError(ex, "Error in BeginListeningForBroadcasts");
}
}
}
@@ -142,11 +139,11 @@ namespace Rssdp.Infrastructure
{
lock (_BroadcastListenSocketSynchroniser)
{
- if (_BroadcastListenSocket != null)
+ if (_BroadcastListenSockets != null)
{
_logger.LogInformation("{0} disposing _BroadcastListenSocket", GetType().Name);
- _BroadcastListenSocket.Dispose();
- _BroadcastListenSocket = null;
+ _BroadcastListenSockets.ForEach(s => s.Dispose());
+ _BroadcastListenSockets = null;
}
}
}
@@ -336,20 +333,46 @@ namespace Rssdp.Infrastructure
return Task.CompletedTask;
}
- private ISocket ListenForBroadcastsAsync()
+ private List<ISocket> ListenForBroadcasts()
{
- var socket = _SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), _MulticastTtl, SsdpConstants.MulticastPort);
- _ = ListenToSocketInternal(socket);
+ var sockets = new List<ISocket>();
+ if (_enableMultiSocketBinding)
+ {
+ foreach (var address in _networkManager.GetInternalBindAddresses())
+ {
+ if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ // Not support IPv6 right now
+ continue;
+ }
- return socket;
+ try
+ {
+ sockets.Add(_SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), address.Address, _MulticastTtl, SsdpConstants.MulticastPort));
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error in ListenForBroadcasts. IPAddress: {0}", address);
+ }
+ }
+ }
+ else
+ {
+ sockets.Add(_SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), IPAddress.Any, _MulticastTtl, SsdpConstants.MulticastPort));
+ }
+
+ foreach (var socket in sockets)
+ {
+ _ = ListenToSocketInternal(socket);
+ }
+
+ return sockets;
}
private List<ISocket> CreateSocketAndListenForResponsesAsync()
{
var sockets = new List<ISocket>();
- sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IPAddress.Any, _LocalPort));
-
if (_enableMultiSocketBinding)
{
foreach (var address in _networkManager.GetInternalBindAddresses())
@@ -370,6 +393,10 @@ namespace Rssdp.Infrastructure
}
}
}
+ else
+ {
+ sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IPAddress.Any, _LocalPort));
+ }
foreach (var socket in sockets)
{
diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs
index a7767b3c0..adaac5fa3 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,7 @@ 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))
+ if (!_sendOnlyMatchedHost || root.Address.Equals(remoteEndPoint.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 aa2dbc57a..000000000
--- 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
- {
- /// <summary>
- /// Checks IP address formats.
- /// </summary>
- /// <param name="address">IP Address.</param>
- [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();
-
- /// <summary>
- /// All should be invalid address strings.
- /// </summary>
- /// <param name="address">Invalid address strings.</param>
- [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
index ec3a1300c..c81fdefe9 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
{
/// <summary>
/// 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();
/// <summary>
/// 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 8174632bb..241d2314b 100644
--- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs
+++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs
@@ -1,5 +1,6 @@
using System;
-using System.Collections.ObjectModel;
+using System.Collections.Generic;
+using System.Linq;
using System.Net;
using Jellyfin.Networking.Configuration;
using Jellyfin.Networking.Manager;
@@ -34,6 +35,8 @@ namespace Jellyfin.Networking.Tests
[InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24;200.200.200.0/24", "[192.168.1.208/24,200.200.200.200/24]")]
// eth16 only
[InlineData("192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")]
+ // eth16 only without mask
+ [InlineData("192.168.1.208,-16,eth16|200.200.200.200,11,eth11", "192.168.1.0/24", "[192.168.1.208/32]")]
// All interfaces excluded. (including loopbacks)
[InlineData("192.168.1.208/24,-16,vEthernet1|192.168.2.208/24,-16,vEthernet212|200.200.200.200/24,11,eth11", "192.168.1.0/24", "[]")]
// vEthernet1 and vEthernet212 should be excluded.
@@ -53,152 +56,88 @@ namespace Jellyfin.Networking.Tests
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
NetworkManager.MockNetworkSettings = string.Empty;
- Assert.Equal(nm.GetInternalBindAddresses().AsString(), value);
+ Assert.Equal(value, "[" + string.Join(",", nm.GetInternalBindAddresses().Select(x => x.Address + "/" + x.Subnet.PrefixLength)) + "]");
}
/// <summary>
- /// Test collection parsing.
+ /// Checks valid IP address formats.
/// </summary>
- /// <param name="settings">Collection to parse.</param>
- /// <param name="result1">Included addresses from the collection.</param>
- /// <param name="result2">Included IP4 addresses from the collection.</param>
- /// <param name="result3">Excluded addresses from the collection.</param>
- /// <param name="result4">Excluded IP4 addresses from the collection.</param>
- /// <param name="result5">Network addresses of the collection.</param>
+ /// <param name="address">IP Address.</param>
[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)
- {
- ArgumentNullException.ThrowIfNull(settings);
-
- var conf = new NetworkConfiguration()
- {
- EnableIPV6 = true,
- EnableIPV4 = true,
- };
-
- using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
-
- // Test included.
- Collection<IPObject> 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);
- }
+ [InlineData("127.0.0.1")]
+ [InlineData("127.0.0.1/8")]
+ [InlineData("192.168.1.2")]
+ [InlineData("192.168.1.2/24")]
+ [InlineData("192.168.1.2/255.255.255.0")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")]
+ [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]")]
+ [InlineData("fe80::7add:12ff:febb:c67b%16")]
+ [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")]
+ [InlineData("fe80::7add:12ff:febb:c67b%16:123")]
+ [InlineData("[fe80::7add:12ff:febb:c67b%16]")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")]
+ public static void TryParseValidIPStringsTrue(string address)
+ => Assert.True(NetworkExtensions.TryParseToSubnet(address, out _));
/// <summary>
- /// Union two collections.
+ /// Checks invalid IP address formats.
/// </summary>
- /// <param name="settings">Source.</param>
- /// <param name="compare">Destination.</param>
- /// <param name="result">Result.</param>
+ /// <param name="address">IP Address.</param>
[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)
- {
- ArgumentNullException.ThrowIfNull(settings);
-
- ArgumentNullException.ThrowIfNull(compare);
-
- ArgumentNullException.ThrowIfNull(result);
-
- var conf = new NetworkConfiguration()
- {
- EnableIPV6 = true,
- EnableIPV4 = true,
- };
-
- using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
-
- Collection<IPObject> nc1 = nm.CreateIPCollection(settings.Split(','), false);
- Collection<IPObject> nc2 = nm.CreateIPCollection(compare.Split(','), false);
-
- Assert.Equal(nc1.ThatAreContainedInNetworks(nc2).AsString(), result);
- }
+ [InlineData("127.0.0.1#")]
+ [InlineData("localhost!")]
+ [InlineData("256.128.0.0.0.1")]
+ [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")]
+ [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")]
+ public static void TryParseInvalidIPStringsFalse(string address)
+ => Assert.False(NetworkExtensions.TryParseToSubnet(address, out _));
+ /// <summary>
+ /// Checks if IPv4 address is within a defined subnet.
+ /// </summary>
+ /// <param name="netMask">Network mask.</param>
+ /// <param name="ipAddress">IP Address.</param>
[Theory]
[InlineData("192.168.5.85/24", "192.168.5.1")]
[InlineData("192.168.5.85/24", "192.168.5.254")]
+ [InlineData("192.168.5.85/255.255.255.0", "192.168.5.254")]
[InlineData("10.128.240.50/30", "10.128.240.48")]
[InlineData("10.128.240.50/30", "10.128.240.49")]
[InlineData("10.128.240.50/30", "10.128.240.50")]
[InlineData("10.128.240.50/30", "10.128.240.51")]
+ [InlineData("10.128.240.50/255.255.255.252", "10.128.240.51")]
[InlineData("127.0.0.1/8", "127.0.0.1")]
public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress)
{
- var ipAddressObj = IPNetAddress.Parse(netMask);
- Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ var ipa = IPAddress.Parse(ipAddress);
+ Assert.True(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress)));
}
+ /// <summary>
+ /// Checks if IPv4 address is not within a defined subnet.
+ /// </summary>
+ /// <param name="netMask">Network mask.</param>
+ /// <param name="ipAddress">IP Address.</param>
[Theory]
[InlineData("192.168.5.85/24", "192.168.4.254")]
[InlineData("192.168.5.85/24", "191.168.5.254")]
+ [InlineData("192.168.5.85/255.255.255.252", "192.168.4.254")]
[InlineData("10.128.240.50/30", "10.128.240.47")]
[InlineData("10.128.240.50/30", "10.128.240.52")]
[InlineData("10.128.240.50/30", "10.128.239.50")]
[InlineData("10.128.240.50/30", "10.127.240.51")]
+ [InlineData("10.128.240.50/255.255.255.252", "10.127.240.51")]
public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress)
{
- var ipAddressObj = IPNetAddress.Parse(netMask);
- Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ var ipa = IPAddress.Parse(ipAddress);
+ Assert.False(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress)));
}
+ /// <summary>
+ /// Checks if IPv6 address is within a defined subnet.
+ /// </summary>
+ /// <param name="netMask">Network mask.</param>
+ /// <param name="ipAddress">IP Address.</param>
[Theory]
[InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")]
[InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFFF")]
@@ -207,8 +146,7 @@ namespace Jellyfin.Networking.Tests
[InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")]
public void IpV6SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress)
{
- var ipAddressObj = IPNetAddress.Parse(netMask);
- Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ Assert.True(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress)));
}
[Theory]
@@ -219,77 +157,14 @@ 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)));
- }
-
- [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));
+ Assert.False(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress)));
}
[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)
- {
- ArgumentNullException.ThrowIfNull(source);
-
- ArgumentNullException.ThrowIfNull(dest);
-
- ArgumentNullException.ThrowIfNull(result);
-
- var conf = new NetworkConfiguration()
- {
- EnableIPV6 = true,
- EnableIPV4 = true
- };
-
- using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
-
- // Test included, IP6.
- Collection<IPObject> ncSource = nm.CreateIPCollection(source.Split(','));
- Collection<IPObject> ncDest = nm.CreateIPCollection(dest.Split(','));
- Collection<IPObject> ncResult = ncSource.ThatAreContainedInNetworks(ncDest);
- Collection<IPObject> 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")]
@@ -327,14 +202,14 @@ namespace Jellyfin.Networking.Tests
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
NetworkManager.MockNetworkSettings = string.Empty;
- _ = nm.TryParseInterface(result, out Collection<IPObject>? resultObj);
+ _ = nm.TryParseInterface(result, out List<IPData>? 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 is not null && host?.HasAddress == true)
+ if (resultObj is not 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);
@@ -363,8 +238,8 @@ namespace Jellyfin.Networking.Tests
// User on external network, internal binding only - so assumption is a proxy forward, return external override.
[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 overridden.
- [InlineData("jellyfin.org", "192.168.1.0/24", "", 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")]
// 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")]
@@ -390,15 +265,15 @@ namespace Jellyfin.Networking.Tests
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
NetworkManager.MockNetworkSettings = string.Empty;
- if (nm.TryParseInterface(result, out Collection<IPObject>? resultObj) && resultObj is not null)
+ if (nm.TryParseInterface(result, out List<IPData>? resultObj) && resultObj is not null)
{
- // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks).
- result = ((IPNetAddress)resultObj[0]).ToString(true);
+ // Parse out IPAddresses so we can do a string comparison (ignore subnet masks).
+ result = resultObj.First().Address.ToString();
}
var intf = nm.GetBindInterface(source, out int? _);
- Assert.Equal(intf, result);
+ Assert.Equal(result, intf);
}
[Theory]
@@ -425,6 +300,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.
diff --git a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs
index a1bdfa31b..12a9beb9e 100644
--- a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs
+++ b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs
@@ -21,9 +21,9 @@ namespace Jellyfin.Server.Tests
data.Add(
true,
true,
- new string[] { "192.168.t", "127.0.0.1", "1234.1232.12.1234" },
- new IPAddress[] { IPAddress.Loopback.MapToIPv6() },
- Array.Empty<IPNetwork>());
+ new string[] { "192.168.t", "127.0.0.1", "::1", "1234.1232.12.1234" },
+ new IPAddress[] { IPAddress.Loopback },
+ new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) });
data.Add(
true,
@@ -64,7 +64,7 @@ namespace Jellyfin.Server.Tests
true,
true,
new string[] { "localhost" },
- new IPAddress[] { IPAddress.Loopback.MapToIPv6() },
+ new IPAddress[] { IPAddress.Loopback },
new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) });
return data;
}