diff --git a/Directory.Packages.props b/Directory.Packages.props
index 25748c541c..0bd7b6e9c2 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -24,6 +24,7 @@
+
diff --git a/Emby.Dlna/Configuration/DlnaOptions.cs b/Emby.Dlna/Configuration/DlnaOptions.cs
index e95a878c67..f233468de3 100644
--- a/Emby.Dlna/Configuration/DlnaOptions.cs
+++ b/Emby.Dlna/Configuration/DlnaOptions.cs
@@ -17,7 +17,7 @@ namespace Emby.Dlna.Configuration
BlastAliveMessages = true;
SendOnlyMatchedHost = true;
ClientDiscoveryIntervalSeconds = 60;
- AliveMessageIntervalSeconds = 1800;
+ AliveMessageIntervalSeconds = 180;
}
///
diff --git a/Emby.Dlna/Main/DlnaEntryPoint.cs b/Emby.Dlna/Main/DlnaEntryPoint.cs
index 39cfc2d1d4..f6ec9574b6 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;
@@ -201,8 +200,7 @@ namespace Emby.Dlna.Main
{
if (_communicationsServer is null)
{
- var enableMultiSocketBinding = OperatingSystem.IsWindows() ||
- OperatingSystem.IsLinux();
+ var enableMultiSocketBinding = OperatingSystem.IsWindows() || OperatingSystem.IsLinux();
_communicationsServer = new SsdpCommunicationsServer(_socketFactory, _networkManager, _logger, enableMultiSocketBinding)
{
@@ -248,11 +246,6 @@ namespace Emby.Dlna.Main
public void StartDevicePublisher(Configuration.DlnaOptions options)
{
- if (!options.BlastAliveMessages)
- {
- return;
- }
-
if (_publisher is not null)
{
return;
@@ -263,7 +256,8 @@ namespace Emby.Dlna.Main
_publisher = new SsdpDevicePublisher(
_communicationsServer,
Environment.OSVersion.Platform.ToString(),
- Environment.OSVersion.VersionString,
+ // Can not use VersionString here since that includes OS and version
+ Environment.OSVersion.Version.ToString(),
_config.GetDlnaConfiguration().SendOnlyMatchedHost)
{
LogFunction = (msg) => _logger.LogDebug("{Msg}", msg),
@@ -272,7 +266,10 @@ namespace Emby.Dlna.Main
RegisterServerEndpoints();
- _publisher.StartBroadcastingAliveMessages(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds));
+ if (options.BlastAliveMessages)
+ {
+ _publisher.StartSendingAliveNotifications(TimeSpan.FromSeconds(options.BlastAliveMessageIntervalSeconds));
+ }
}
catch (Exception ex)
{
@@ -285,42 +282,33 @@ 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
+ // IPv6 is currently unsupported
+ var validInterfaces = _networkManager.GetInternalBindAddresses()
+ .Where(x => x.Address is not null)
+ .Where(x => x.AddressFamily != AddressFamily.InterNetworkV6)
+ .ToList();
- if (bindAddresses.Count == 0)
+ if (validInterfaces.Count == 0)
{
- // No interfaces returned, so use loopback.
- bindAddresses = _networkManager.GetLoopbacks();
+ // No interfaces returned, fall back to loopback
+ validInterfaces = _networkManager.GetLoopbacks().ToList();
}
- foreach (IPNetAddress address in bindAddresses)
+ foreach (var intf in validInterfaces)
{
- if (address.AddressFamily == AddressFamily.InterNetworkV6)
- {
- // Not supporting IPv6 right now
- 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, intf.Address);
- var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(address, false) + descriptorUri);
+ var uri = new UriBuilder(_appHost.GetApiUrlForLocalAccess(intf.Address, false) + descriptorUri);
var device = new SsdpRootDevice
{
CacheLifetime = TimeSpan.FromSeconds(1800), // How long SSDP clients can cache this info.
Location = uri.Uri, // Must point to the URL that serves your devices UPnP description document.
- Address = address.Address,
- PrefixLength = address.PrefixLength,
+ Address = intf.Address,
+ PrefixLength = NetworkExtensions.MaskToCidr(intf.Subnet.Prefix),
FriendlyName = "Jellyfin",
Manufacturer = "Jellyfin",
ModelName = "Jellyfin Server",
diff --git a/Emby.Dlna/PlayTo/PlayToManager.cs b/Emby.Dlna/PlayTo/PlayToManager.cs
index b469c9cb06..241dff5ae3 100644
--- a/Emby.Dlna/PlayTo/PlayToManager.cs
+++ b/Emby.Dlna/PlayTo/PlayToManager.cs
@@ -189,7 +189,7 @@ namespace Emby.Dlna.PlayTo
_sessionManager.UpdateDeviceName(sessionInfo.Id, deviceName);
- string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIpAddress);
+ string serverAddress = _appHost.GetSmartApiUrl(info.RemoteIPAddress);
controller = new PlayToController(
sessionInfo,
diff --git a/Emby.Dlna/Ssdp/DeviceDiscovery.cs b/Emby.Dlna/Ssdp/DeviceDiscovery.cs
index 8a4e5ff455..4fbbc38859 100644
--- a/Emby.Dlna/Ssdp/DeviceDiscovery.cs
+++ b/Emby.Dlna/Ssdp/DeviceDiscovery.cs
@@ -73,7 +73,11 @@ namespace Emby.Dlna.Ssdp
{
if (_listenerCount > 0 && _deviceLocator is null && _commsServer is not null)
{
- _deviceLocator = new SsdpDeviceLocator(_commsServer);
+ _deviceLocator = new SsdpDeviceLocator(
+ _commsServer,
+ Environment.OSVersion.Platform.ToString(),
+ // Can not use VersionString here since that includes OS and version
+ Environment.OSVersion.Version.ToString());
// (Optional) Set the filter so we only see notifications for devices we care about
// (can be any search target value i.e device type, uuid value etc - any value that appears in the
@@ -106,7 +110,7 @@ namespace Emby.Dlna.Ssdp
{
Location = e.DiscoveredDevice.DescriptionLocation,
Headers = headers,
- RemoteIpAddress = e.RemoteIpAddress
+ RemoteIPAddress = e.RemoteIPAddress
});
DeviceDiscoveredInternal?.Invoke(this, args);
diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs
index 7969577bc0..dd90a89505 100644
--- a/Emby.Server.Implementations/ApplicationHost.cs
+++ b/Emby.Server.Implementations/ApplicationHost.cs
@@ -475,8 +475,8 @@ namespace Emby.Server.Implementations
}
var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
- HttpPort = networkConfiguration.HttpServerPortNumber;
- HttpsPort = networkConfiguration.HttpsPortNumber;
+ HttpPort = networkConfiguration.InternalHttpPort;
+ HttpsPort = networkConfiguration.InternalHttpsPort;
// Safeguard against invalid configuration
if (HttpPort == HttpsPort)
@@ -785,8 +785,8 @@ namespace Emby.Server.Implementations
if (HttpPort != 0 && HttpsPort != 0)
{
// Need to restart if ports have changed
- if (networkConfiguration.HttpServerPortNumber != HttpPort
- || networkConfiguration.HttpsPortNumber != HttpsPort)
+ if (networkConfiguration.InternalHttpPort != HttpPort
+ || networkConfiguration.InternalHttpsPort != HttpsPort)
{
if (ConfigurationManager.Configuration.IsPortAuthorized)
{
@@ -995,7 +995,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);
}
@@ -1006,7 +1006,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;
}
@@ -1027,15 +1029,15 @@ namespace Emby.Server.Implementations
return PublishedServerUrl.Trim('/');
}
- string smart = NetManager.GetBindInterface(hostname, out var port);
+ string smart = NetManager.GetBindAddress(hostname, out var port);
return GetLocalApiUrl(smart.Trim('/'), null, port);
}
///
- 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 _, true);
var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
int? port = !allowHttps ? HttpPort : null;
return GetLocalApiUrl(smart, scheme, port);
diff --git a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
index 06e57ad127..d6da597b8b 100644
--- a/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
+++ b/Emby.Server.Implementations/EntryPoints/ExternalPortForwarding.cs
@@ -57,7 +57,7 @@ namespace Emby.Server.Implementations.EntryPoints
return new StringBuilder(32)
.Append(config.EnableUPnP).Append(Separator)
- .Append(config.PublicPort).Append(Separator)
+ .Append(config.PublicHttpPort).Append(Separator)
.Append(config.PublicHttpsPort).Append(Separator)
.Append(_appHost.HttpPort).Append(Separator)
.Append(_appHost.HttpsPort).Append(Separator)
@@ -146,7 +146,7 @@ namespace Emby.Server.Implementations.EntryPoints
private IEnumerable CreatePortMaps(INatDevice device)
{
var config = _config.GetNetworkConfiguration();
- yield return CreatePortMap(device, _appHost.HttpPort, config.PublicPort);
+ yield return CreatePortMap(device, _appHost.HttpPort, config.PublicHttpPort);
if (_appHost.ListenWithHttps)
{
diff --git a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
index e45baedd7f..2839e163e3 100644
--- a/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
+++ b/Emby.Server.Implementations/EntryPoints/UdpServerEntryPoint.cs
@@ -1,10 +1,14 @@
using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
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 +33,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;
///
/// The UDP server.
///
- private UdpServer? _udpServer;
+ private List _udpServers;
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private bool _disposed = false;
@@ -44,16 +50,21 @@ namespace Emby.Server.Implementations.EntryPoints
/// Instance of the interface.
/// Instance of the interface.
/// Instance of the interface.
+ /// Instance of the interface.
public UdpServerEntryPoint(
ILogger logger,
IServerApplicationHost appHost,
IConfiguration configuration,
- IConfigurationManager configurationManager)
+ IConfigurationManager configurationManager,
+ INetworkManager networkManager)
{
_logger = logger;
_appHost = appHost;
_config = configuration;
_configurationManager = configurationManager;
+ _networkManager = networkManager;
+ _udpServers = new List();
+ _enableMultiSocketBinding = OperatingSystem.IsWindows() || OperatingSystem.IsLinux();
}
///
@@ -68,8 +79,32 @@ namespace Emby.Server.Implementations.EntryPoints
try
{
- _udpServer = new UdpServer(_logger, _appHost, _config, PortNumber);
- _udpServer.Start(_cancellationTokenSource.Token);
+ if (_enableMultiSocketBinding)
+ {
+ // Add global broadcast socket
+ var server = new UdpServer(_logger, _appHost, _config, IPAddress.Broadcast, PortNumber);
+ server.Start(_cancellationTokenSource.Token);
+ _udpServers.Add(server);
+
+ // Add bind address specific broadcast sockets
+ // IPv6 is currently unsupported
+ var validInterfaces = _networkManager.GetInternalBindAddresses().Where(i => i.AddressFamily == AddressFamily.InterNetwork);
+ foreach (var intf in validInterfaces)
+ {
+ var broadcastAddress = NetworkExtensions.GetBroadcastAddress(intf.Subnet);
+ _logger.LogDebug("Binding UDP server to {Address} on port {PortNumber}", broadcastAddress, PortNumber);
+
+ server = new UdpServer(_logger, _appHost, _config, broadcastAddress, PortNumber);
+ server.Start(_cancellationTokenSource.Token);
+ _udpServers.Add(server);
+ }
+ }
+ else
+ {
+ var server = new UdpServer(_logger, _appHost, _config, IPAddress.Any, PortNumber);
+ server.Start(_cancellationTokenSource.Token);
+ _udpServers.Add(server);
+ }
}
catch (SocketException ex)
{
@@ -97,9 +132,12 @@ namespace Emby.Server.Implementations.EntryPoints
_cancellationTokenSource.Cancel();
_cancellationTokenSource.Dispose();
- _udpServer?.Dispose();
- _udpServer = null;
+ foreach (var server in _udpServers)
+ {
+ server.Dispose();
+ }
+ _udpServers.Clear();
_disposed = true;
}
}
diff --git a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs
index 4f7d1c40a6..ecfb242f6f 100644
--- a/Emby.Server.Implementations/HttpServer/WebSocketManager.cs
+++ b/Emby.Server.Implementations/HttpServer/WebSocketManager.cs
@@ -51,7 +51,7 @@ namespace Emby.Server.Implementations.HttpServer
using var connection = new WebSocketConnection(
_loggerFactory.CreateLogger(),
webSocket,
- context.GetNormalizedRemoteIp())
+ context.GetNormalizedRemoteIP())
{
OnReceive = ProcessWebSocketMessageReceived
};
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
index 98bbc15406..1795e85a3c 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs
@@ -661,18 +661,18 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
// Need a way to set the Receive timeout on the socket otherwise this might never timeout?
try
{
- await udpClient.SendToAsync(discBytes, 0, discBytes.Length, new IPEndPoint(IPAddress.Parse("255.255.255.255"), 65001), cancellationToken).ConfigureAwait(false);
+ await udpClient.SendToAsync(discBytes, new IPEndPoint(IPAddress.Broadcast, 65001), cancellationToken).ConfigureAwait(false);
var receiveBuffer = new byte[8192];
while (!cancellationToken.IsCancellationRequested)
{
- var response = await udpClient.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken).ConfigureAwait(false);
- var deviceIp = response.RemoteEndPoint.Address.ToString();
+ var response = await udpClient.ReceiveMessageFromAsync(receiveBuffer, new IPEndPoint(IPAddress.Any, 0), cancellationToken).ConfigureAwait(false);
+ var deviceIP = ((IPEndPoint)response.RemoteEndPoint).Address.ToString();
- // check to make sure we have enough bytes received to be a valid message and make sure the 2nd byte is the discover reply byte
- if (response.ReceivedBytes > 13 && response.Buffer[1] == 3)
+ // Check to make sure we have enough bytes received to be a valid message and make sure the 2nd byte is the discover reply byte
+ if (response.ReceivedBytes > 13 && receiveBuffer[1] == 3)
{
- var deviceAddress = "http://" + deviceIp;
+ var deviceAddress = "http://" + deviceIP;
var info = await TryGetTunerHostInfo(deviceAddress, cancellationToken).ConfigureAwait(false);
diff --git a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs
index 7bc209d6bd..a8b090635e 100644
--- a/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs
+++ b/Emby.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunManager.cs
@@ -48,10 +48,10 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
GC.SuppressFinalize(this);
}
- public async Task CheckTunerAvailability(IPAddress remoteIp, int tuner, CancellationToken cancellationToken)
+ public async Task CheckTunerAvailability(IPAddress remoteIP, int tuner, CancellationToken cancellationToken)
{
using var client = new TcpClient();
- await client.ConnectAsync(remoteIp, HdHomeRunPort, cancellationToken).ConfigureAwait(false);
+ await client.ConnectAsync(remoteIP, HdHomeRunPort, cancellationToken).ConfigureAwait(false);
using var stream = client.GetStream();
return await CheckTunerAvailability(stream, tuner, cancellationToken).ConfigureAwait(false);
@@ -75,9 +75,9 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
}
}
- public async Task StartStreaming(IPAddress remoteIp, IPAddress localIp, int localPort, IHdHomerunChannelCommands commands, int numTuners, CancellationToken cancellationToken)
+ public async Task StartStreaming(IPAddress remoteIP, IPAddress localIP, int localPort, IHdHomerunChannelCommands commands, int numTuners, CancellationToken cancellationToken)
{
- _remoteEndPoint = new IPEndPoint(remoteIp, HdHomeRunPort);
+ _remoteEndPoint = new IPEndPoint(remoteIP, HdHomeRunPort);
_tcpClient = new TcpClient();
await _tcpClient.ConnectAsync(_remoteEndPoint, cancellationToken).ConfigureAwait(false);
@@ -125,7 +125,7 @@ namespace Emby.Server.Implementations.LiveTv.TunerHosts.HdHomerun
}
}
- var targetValue = string.Format(CultureInfo.InvariantCulture, "rtp://{0}:{1}", localIp, localPort);
+ var targetValue = string.Format(CultureInfo.InvariantCulture, "rtp://{0}:{1}", localIP, localPort);
var targetMsgLen = WriteSetMessage(buffer, i, "target", targetValue, lockKeyValue);
await stream.WriteAsync(buffer.AsMemory(0, targetMsgLen), cancellationToken).ConfigureAwait(false);
diff --git a/Emby.Server.Implementations/Net/SocketFactory.cs b/Emby.Server.Implementations/Net/SocketFactory.cs
index 303875df55..51e92953df 100644
--- a/Emby.Server.Implementations/Net/SocketFactory.cs
+++ b/Emby.Server.Implementations/Net/SocketFactory.cs
@@ -10,60 +10,63 @@ namespace Emby.Server.Implementations.Net
public class SocketFactory : ISocketFactory
{
///
- public ISocket CreateUdpBroadcastSocket(int localPort)
+ public Socket CreateUdpBroadcastSocket(int localPort)
{
if (localPort < 0)
{
throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
}
- var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
+ var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
- retVal.EnableBroadcast = true;
- retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
- retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
+ socket.EnableBroadcast = true;
+ socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
+ socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
+ socket.Bind(new IPEndPoint(IPAddress.Any, localPort));
- return new UdpSocket(retVal, localPort, IPAddress.Any);
+ return socket;
}
catch
{
- retVal?.Dispose();
+ socket?.Dispose();
throw;
}
}
///
- public ISocket CreateSsdpUdpSocket(IPAddress localIp, int localPort)
+ public Socket CreateSsdpUdpSocket(IPData bindInterface, int localPort)
{
+ ArgumentNullException.ThrowIfNull(bindInterface.Address);
+
if (localPort < 0)
{
throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
}
- var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
+ var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
- retVal.EnableBroadcast = true;
- retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
- retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
+ socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
+ socket.Bind(new IPEndPoint(bindInterface.Address, localPort));
- retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), localIp));
- return new UdpSocket(retVal, localPort, localIp);
+ return socket;
}
catch
{
- retVal?.Dispose();
+ socket?.Dispose();
throw;
}
}
///
- public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, int multicastTimeToLive, int localPort)
+ public Socket CreateUdpMulticastSocket(IPAddress multicastAddress, IPData bindInterface, int multicastTimeToLive, int localPort)
{
- ArgumentNullException.ThrowIfNull(ipAddress);
+ var bindIPAddress = bindInterface.Address;
+ ArgumentNullException.ThrowIfNull(multicastAddress);
+ ArgumentNullException.ThrowIfNull(bindIPAddress);
if (multicastTimeToLive <= 0)
{
@@ -75,36 +78,26 @@ namespace Emby.Server.Implementations.Net
throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
}
- var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
-
- retVal.ExclusiveAddressUse = false;
+ var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
try
{
- // seeing occasional exceptions thrown on qnap
- // System.Net.Sockets.SocketException (0x80004005): Protocol not available
- retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
- }
- catch (SocketException)
- {
- }
+ var interfaceIndex = bindInterface.Index;
+ var interfaceIndexSwapped = (int)IPAddress.HostToNetworkOrder(interfaceIndex);
- try
- {
- retVal.EnableBroadcast = true;
- // retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
- retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
+ socket.MulticastLoopback = false;
+ socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
+ socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
+ socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
+ socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, interfaceIndexSwapped);
+ socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, interfaceIndex));
+ socket.Bind(new IPEndPoint(multicastAddress, localPort));
- var localIp = IPAddress.Any;
-
- retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ipAddress, localIp));
- retVal.MulticastLoopback = true;
-
- return new UdpSocket(retVal, localPort, localIp);
+ return socket;
}
catch
{
- retVal?.Dispose();
+ socket?.Dispose();
throw;
}
diff --git a/Emby.Server.Implementations/Net/UdpSocket.cs b/Emby.Server.Implementations/Net/UdpSocket.cs
deleted file mode 100644
index 577b79283a..0000000000
--- a/Emby.Server.Implementations/Net/UdpSocket.cs
+++ /dev/null
@@ -1,267 +0,0 @@
-#nullable disable
-
-#pragma warning disable CS1591
-
-using System;
-using System.Net;
-using System.Net.Sockets;
-using System.Threading;
-using System.Threading.Tasks;
-using MediaBrowser.Model.Net;
-
-namespace Emby.Server.Implementations.Net
-{
- // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
- // Be careful to check any changes compile and work for all platform projects it is shared in.
-
- public sealed class UdpSocket : ISocket, IDisposable
- {
- private readonly int _localPort;
-
- private readonly SocketAsyncEventArgs _receiveSocketAsyncEventArgs = new SocketAsyncEventArgs()
- {
- SocketFlags = SocketFlags.None
- };
-
- private readonly SocketAsyncEventArgs _sendSocketAsyncEventArgs = new SocketAsyncEventArgs()
- {
- SocketFlags = SocketFlags.None
- };
-
- private Socket _socket;
- private bool _disposed = false;
- private TaskCompletionSource _currentReceiveTaskCompletionSource;
- private TaskCompletionSource _currentSendTaskCompletionSource;
-
- public UdpSocket(Socket socket, int localPort, IPAddress ip)
- {
- ArgumentNullException.ThrowIfNull(socket);
-
- _socket = socket;
- _localPort = localPort;
- LocalIPAddress = ip;
-
- _socket.Bind(new IPEndPoint(ip, _localPort));
-
- InitReceiveSocketAsyncEventArgs();
- }
-
- public UdpSocket(Socket socket, IPEndPoint endPoint)
- {
- ArgumentNullException.ThrowIfNull(socket);
-
- _socket = socket;
- _socket.Connect(endPoint);
-
- InitReceiveSocketAsyncEventArgs();
- }
-
- public Socket Socket => _socket;
-
- public IPAddress LocalIPAddress { get; }
-
- private void InitReceiveSocketAsyncEventArgs()
- {
- var receiveBuffer = new byte[8192];
- _receiveSocketAsyncEventArgs.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
- _receiveSocketAsyncEventArgs.Completed += OnReceiveSocketAsyncEventArgsCompleted;
-
- var sendBuffer = new byte[8192];
- _sendSocketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
- _sendSocketAsyncEventArgs.Completed += OnSendSocketAsyncEventArgsCompleted;
- }
-
- private void OnReceiveSocketAsyncEventArgsCompleted(object sender, SocketAsyncEventArgs e)
- {
- var tcs = _currentReceiveTaskCompletionSource;
- if (tcs is not null)
- {
- _currentReceiveTaskCompletionSource = null;
-
- if (e.SocketError == SocketError.Success)
- {
- tcs.TrySetResult(new SocketReceiveResult
- {
- Buffer = e.Buffer,
- ReceivedBytes = e.BytesTransferred,
- RemoteEndPoint = e.RemoteEndPoint as IPEndPoint,
- LocalIPAddress = LocalIPAddress
- });
- }
- else
- {
- tcs.TrySetException(new SocketException((int)e.SocketError));
- }
- }
- }
-
- private void OnSendSocketAsyncEventArgsCompleted(object sender, SocketAsyncEventArgs e)
- {
- var tcs = _currentSendTaskCompletionSource;
- if (tcs is not null)
- {
- _currentSendTaskCompletionSource = null;
-
- if (e.SocketError == SocketError.Success)
- {
- tcs.TrySetResult(e.BytesTransferred);
- }
- else
- {
- tcs.TrySetException(new SocketException((int)e.SocketError));
- }
- }
- }
-
- public IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback)
- {
- ThrowIfDisposed();
-
- EndPoint receivedFromEndPoint = new IPEndPoint(IPAddress.Any, 0);
-
- return _socket.BeginReceiveFrom(buffer, offset, count, SocketFlags.None, ref receivedFromEndPoint, callback, buffer);
- }
-
- public int Receive(byte[] buffer, int offset, int count)
- {
- ThrowIfDisposed();
-
- return _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);
- }
-
- public SocketReceiveResult EndReceive(IAsyncResult result)
- {
- ThrowIfDisposed();
-
- var sender = new IPEndPoint(IPAddress.Any, 0);
- var remoteEndPoint = (EndPoint)sender;
-
- var receivedBytes = _socket.EndReceiveFrom(result, ref remoteEndPoint);
-
- var buffer = (byte[])result.AsyncState;
-
- return new SocketReceiveResult
- {
- ReceivedBytes = receivedBytes,
- RemoteEndPoint = (IPEndPoint)remoteEndPoint,
- Buffer = buffer,
- LocalIPAddress = LocalIPAddress
- };
- }
-
- public Task ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- {
- ThrowIfDisposed();
-
- var taskCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
- bool isResultSet = false;
-
- Action callback = callbackResult =>
- {
- try
- {
- if (!isResultSet)
- {
- isResultSet = true;
- taskCompletion.TrySetResult(EndReceive(callbackResult));
- }
- }
- catch (Exception ex)
- {
- taskCompletion.TrySetException(ex);
- }
- };
-
- var result = BeginReceive(buffer, offset, count, new AsyncCallback(callback));
-
- if (result.CompletedSynchronously)
- {
- callback(result);
- return taskCompletion.Task;
- }
-
- cancellationToken.Register(() => taskCompletion.TrySetCanceled());
-
- return taskCompletion.Task;
- }
-
- public Task SendToAsync(byte[] buffer, int offset, int bytes, IPEndPoint endPoint, CancellationToken cancellationToken)
- {
- ThrowIfDisposed();
-
- var taskCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
- bool isResultSet = false;
-
- Action callback = callbackResult =>
- {
- try
- {
- if (!isResultSet)
- {
- isResultSet = true;
- taskCompletion.TrySetResult(EndSendTo(callbackResult));
- }
- }
- catch (Exception ex)
- {
- taskCompletion.TrySetException(ex);
- }
- };
-
- var result = BeginSendTo(buffer, offset, bytes, endPoint, new AsyncCallback(callback), null);
-
- if (result.CompletedSynchronously)
- {
- callback(result);
- return taskCompletion.Task;
- }
-
- cancellationToken.Register(() => taskCompletion.TrySetCanceled());
-
- return taskCompletion.Task;
- }
-
- public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, IPEndPoint endPoint, AsyncCallback callback, object state)
- {
- ThrowIfDisposed();
-
- return _socket.BeginSendTo(buffer, offset, size, SocketFlags.None, endPoint, callback, state);
- }
-
- public int EndSendTo(IAsyncResult result)
- {
- ThrowIfDisposed();
-
- return _socket.EndSendTo(result);
- }
-
- private void ThrowIfDisposed()
- {
- if (_disposed)
- {
- throw new ObjectDisposedException(nameof(UdpSocket));
- }
- }
-
- ///
- public void Dispose()
- {
- if (_disposed)
- {
- return;
- }
-
- _socket?.Dispose();
- _receiveSocketAsyncEventArgs.Dispose();
- _sendSocketAsyncEventArgs.Dispose();
- _currentReceiveTaskCompletionSource?.TrySetCanceled();
- _currentSendTaskCompletionSource?.TrySetCanceled();
-
- _socket = null;
- _currentReceiveTaskCompletionSource = null;
- _currentSendTaskCompletionSource = null;
-
- _disposed = true;
- }
- }
-}
diff --git a/Emby.Server.Implementations/Udp/UdpServer.cs b/Emby.Server.Implementations/Udp/UdpServer.cs
index 937e792f57..a3bbd6df0c 100644
--- a/Emby.Server.Implementations/Udp/UdpServer.cs
+++ b/Emby.Server.Implementations/Udp/UdpServer.cs
@@ -37,18 +37,20 @@ namespace Emby.Server.Implementations.Udp
/// The logger.
/// The application host.
/// The configuration manager.
+ /// The bind address.
/// The port.
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.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs b/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs
index 741b88ea95..3c1401dedc 100644
--- a/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs
+++ b/Jellyfin.Api/Auth/AnonymousLanAccessPolicy/AnonymousLanAccessHandler.cs
@@ -30,7 +30,7 @@ namespace Jellyfin.Api.Auth.AnonymousLanAccessPolicy
///
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, AnonymousLanAccessRequirement requirement)
{
- var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIp();
+ var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIP();
// Loopback will be on LAN, so we can accept null.
if (ip is null || _networkManager.IsInLocalNetwork(ip))
diff --git a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs
index de271ab640..cf3cb69052 100644
--- a/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs
+++ b/Jellyfin.Api/Auth/DefaultAuthorizationPolicy/DefaultAuthorizationHandler.cs
@@ -54,7 +54,7 @@ namespace Jellyfin.Api.Auth.DefaultAuthorizationPolicy
}
var isInLocalNetwork = _httpContextAccessor.HttpContext is not null
- && _networkManager.IsInLocalNetwork(_httpContextAccessor.HttpContext.GetNormalizedRemoteIp());
+ && _networkManager.IsInLocalNetwork(_httpContextAccessor.HttpContext.GetNormalizedRemoteIP());
var user = _userManager.GetUserById(userId);
if (user is null)
{
diff --git a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs
index 6ed6fc90be..557b7d3aa4 100644
--- a/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs
+++ b/Jellyfin.Api/Auth/LocalAccessOrRequiresElevationPolicy/LocalAccessOrRequiresElevationHandler.cs
@@ -31,7 +31,7 @@ namespace Jellyfin.Api.Auth.LocalAccessOrRequiresElevationPolicy
///
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, LocalAccessOrRequiresElevationRequirement requirement)
{
- var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIp();
+ var ip = _httpContextAccessor.HttpContext?.GetNormalizedRemoteIP();
// Loopback will be on LAN, so we can accept null.
if (ip is null || _networkManager.IsInLocalNetwork(ip))
diff --git a/Jellyfin.Api/Controllers/MediaInfoController.cs b/Jellyfin.Api/Controllers/MediaInfoController.cs
index da24616ff3..bea545cfda 100644
--- a/Jellyfin.Api/Controllers/MediaInfoController.cs
+++ b/Jellyfin.Api/Controllers/MediaInfoController.cs
@@ -184,7 +184,7 @@ public class MediaInfoController : BaseJellyfinApiController
enableTranscoding.Value,
allowVideoStreamCopy.Value,
allowAudioStreamCopy.Value,
- Request.HttpContext.GetNormalizedRemoteIp());
+ Request.HttpContext.GetNormalizedRemoteIP());
}
_mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate);
diff --git a/Jellyfin.Api/Controllers/SystemController.cs b/Jellyfin.Api/Controllers/SystemController.cs
index 9ed69f4205..a29790961e 100644
--- a/Jellyfin.Api/Controllers/SystemController.cs
+++ b/Jellyfin.Api/Controllers/SystemController.cs
@@ -189,7 +189,7 @@ public class SystemController : BaseJellyfinApiController
return new EndPointInfo
{
IsLocal = HttpContext.IsLocal(),
- IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp())
+ IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIP())
};
}
diff --git a/Jellyfin.Api/Controllers/UniversalAudioController.cs b/Jellyfin.Api/Controllers/UniversalAudioController.cs
index 2e9035d24f..7177a04403 100644
--- a/Jellyfin.Api/Controllers/UniversalAudioController.cs
+++ b/Jellyfin.Api/Controllers/UniversalAudioController.cs
@@ -138,7 +138,7 @@ public class UniversalAudioController : BaseJellyfinApiController
true,
true,
true,
- Request.HttpContext.GetNormalizedRemoteIp());
+ Request.HttpContext.GetNormalizedRemoteIP());
}
_mediaInfoHelper.SortMediaSources(info, maxStreamingBitrate);
diff --git a/Jellyfin.Api/Controllers/UserController.cs b/Jellyfin.Api/Controllers/UserController.cs
index 530bd96031..4f61af35e0 100644
--- a/Jellyfin.Api/Controllers/UserController.cs
+++ b/Jellyfin.Api/Controllers/UserController.cs
@@ -134,7 +134,7 @@ public class UserController : BaseJellyfinApiController
return NotFound("User not found");
}
- var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIp().ToString());
+ var result = _userManager.GetUserDto(user, HttpContext.GetNormalizedRemoteIP().ToString());
return result;
}
@@ -217,7 +217,7 @@ public class UserController : BaseJellyfinApiController
DeviceId = auth.DeviceId,
DeviceName = auth.Device,
Password = request.Pw,
- RemoteEndPoint = HttpContext.GetNormalizedRemoteIp().ToString(),
+ RemoteEndPoint = HttpContext.GetNormalizedRemoteIP().ToString(),
Username = request.Username
}).ConfigureAwait(false);
@@ -226,7 +226,7 @@ public class UserController : BaseJellyfinApiController
catch (SecurityException e)
{
// rethrow adding IP address to message
- throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e);
+ throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIP()}] {e.Message}", e);
}
}
@@ -248,7 +248,7 @@ public class UserController : BaseJellyfinApiController
catch (SecurityException e)
{
// rethrow adding IP address to message
- throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIp()}] {e.Message}", e);
+ throw new SecurityException($"[{HttpContext.GetNormalizedRemoteIP()}] {e.Message}", e);
}
}
@@ -294,7 +294,7 @@ public class UserController : BaseJellyfinApiController
user.Username,
request.CurrentPw ?? string.Empty,
request.CurrentPw ?? string.Empty,
- HttpContext.GetNormalizedRemoteIp().ToString(),
+ HttpContext.GetNormalizedRemoteIP().ToString(),
false).ConfigureAwait(false);
if (success is null)
@@ -475,7 +475,7 @@ public class UserController : BaseJellyfinApiController
await _userManager.ChangePassword(newUser, request.Password).ConfigureAwait(false);
}
- var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIp().ToString());
+ var result = _userManager.GetUserDto(newUser, HttpContext.GetNormalizedRemoteIP().ToString());
return result;
}
@@ -490,7 +490,7 @@ public class UserController : BaseJellyfinApiController
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task> ForgotPassword([FromBody, Required] ForgotPasswordDto forgotPasswordRequest)
{
- var ip = HttpContext.GetNormalizedRemoteIp();
+ var ip = HttpContext.GetNormalizedRemoteIP();
var isLocal = HttpContext.IsLocal()
|| _networkManager.IsInLocalNetwork(ip);
@@ -571,7 +571,7 @@ public class UserController : BaseJellyfinApiController
if (filterByNetwork)
{
- if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp()))
+ if (!_networkManager.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIP()))
{
users = users.Where(i => i.HasPermission(PermissionKind.EnableRemoteAccess));
}
@@ -579,7 +579,7 @@ public class UserController : BaseJellyfinApiController
var result = users
.OrderBy(u => u.Username)
- .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIp().ToString()));
+ .Select(i => _userManager.GetUserDto(i, HttpContext.GetNormalizedRemoteIP().ToString()));
return result;
}
diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
index 646bf6443c..63667e7e69 100644
--- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
+++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs
@@ -284,7 +284,7 @@ public class DynamicHlsHelper
}
}
- if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.GetNormalizedRemoteIp()))
+ if (EnableAdaptiveBitrateStreaming(state, isLiveStream, enableAdaptiveBitrateStreaming, _httpContextAccessor.HttpContext.GetNormalizedRemoteIP()))
{
var requestedVideoBitrate = state.VideoRequest is null ? 0 : state.VideoRequest.VideoBitRate ?? 0;
diff --git a/Jellyfin.Api/Helpers/MediaInfoHelper.cs b/Jellyfin.Api/Helpers/MediaInfoHelper.cs
index 5910d80737..a36028cfeb 100644
--- a/Jellyfin.Api/Helpers/MediaInfoHelper.cs
+++ b/Jellyfin.Api/Helpers/MediaInfoHelper.cs
@@ -421,7 +421,7 @@ public class MediaInfoHelper
true,
true,
true,
- httpContext.GetNormalizedRemoteIp());
+ httpContext.GetNormalizedRemoteIP());
}
else
{
@@ -487,7 +487,7 @@ public class MediaInfoHelper
{
var isInLocalNetwork = _networkManager.IsInLocalNetwork(ipAddress);
- _logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIp: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, ipAddress, isInLocalNetwork);
+ _logger.LogInformation("RemoteClientBitrateLimit: {0}, RemoteIP: {1}, IsInLocalNetwork: {2}", remoteClientMaxBitrate, ipAddress, isInLocalNetwork);
if (!isInLocalNetwork)
{
maxBitrate = Math.Min(maxBitrate ?? remoteClientMaxBitrate, remoteClientMaxBitrate);
diff --git a/Jellyfin.Api/Helpers/RequestHelpers.cs b/Jellyfin.Api/Helpers/RequestHelpers.cs
index 57098edbae..bc12ca3889 100644
--- a/Jellyfin.Api/Helpers/RequestHelpers.cs
+++ b/Jellyfin.Api/Helpers/RequestHelpers.cs
@@ -125,7 +125,7 @@ public static class RequestHelpers
httpContext.User.GetVersion(),
httpContext.User.GetDeviceId(),
httpContext.User.GetDevice(),
- httpContext.GetNormalizedRemoteIp().ToString(),
+ httpContext.GetNormalizedRemoteIP().ToString(),
user).ConfigureAwait(false);
if (session is null)
diff --git a/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs b/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs
index f45b6b5c0a..27bcd5570c 100644
--- a/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs
+++ b/Jellyfin.Api/Middleware/IpBasedAccessValidationMiddleware.cs
@@ -9,15 +9,15 @@ namespace Jellyfin.Api.Middleware;
///
/// Validates the IP of requests coming from local networks wrt. remote access.
///
-public class IpBasedAccessValidationMiddleware
+public class IPBasedAccessValidationMiddleware
{
private readonly RequestDelegate _next;
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// The next delegate in the pipeline.
- public IpBasedAccessValidationMiddleware(RequestDelegate next)
+ public IPBasedAccessValidationMiddleware(RequestDelegate next)
{
_next = next;
}
@@ -37,9 +37,9 @@ public class IpBasedAccessValidationMiddleware
return;
}
- var remoteIp = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
+ var remoteIP = httpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback;
- if (!networkManager.HasRemoteAccess(remoteIp))
+ if (!networkManager.HasRemoteAccess(remoteIP))
{
return;
}
diff --git a/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs b/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs
index 9c2194fafd..94de30d1b1 100644
--- a/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs
+++ b/Jellyfin.Api/Middleware/LanFilteringMiddleware.cs
@@ -38,7 +38,7 @@ public class LanFilteringMiddleware
return;
}
- var host = httpContext.GetNormalizedRemoteIp();
+ var host = httpContext.GetNormalizedRemoteIP();
if (!networkManager.IsInLocalNetwork(host))
{
return;
diff --git a/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs b/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs
index db39177436..279ea70d80 100644
--- a/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs
+++ b/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs
@@ -51,9 +51,9 @@ public class ResponseTimeMiddleware
if (enableWarning && responseTimeMs > warningThreshold && _logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug(
- "Slow HTTP Response from {Url} to {RemoteIp} in {Elapsed:g} with Status Code {StatusCode}",
+ "Slow HTTP Response from {Url} to {RemoteIP} in {Elapsed:g} with Status Code {StatusCode}",
context.Request.GetDisplayUrl(),
- context.GetNormalizedRemoteIp(),
+ context.GetNormalizedRemoteIP(),
responseTime,
context.Response.StatusCode);
}
diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs
index 361dbc8142..573c36be79 100644
--- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs
+++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs
@@ -10,32 +10,17 @@ namespace Jellyfin.Networking.Configuration
public class NetworkConfiguration
{
///
- /// The default value for .
+ /// The default value for .
///
public const int DefaultHttpPort = 8096;
///
- /// The default value for and .
+ /// The default value for and .
///
public const int DefaultHttpsPort = 8920;
private string _baseUrl = string.Empty;
- ///
- /// Gets or sets a value indicating whether the server should force connections over HTTPS.
- ///
- public bool RequireHttps { get; set; }
-
- ///
- /// Gets or sets the filesystem path of an X.509 certificate to use for SSL.
- ///
- public string CertificatePath { get; set; } = string.Empty;
-
- ///
- /// Gets or sets the password required to access the X.509 certificate data in the file specified by .
- ///
- public string CertificatePassword { get; set; } = string.Empty;
-
///
/// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at.
///
@@ -69,24 +54,6 @@ namespace Jellyfin.Networking.Configuration
}
}
- ///
- /// Gets or sets the public HTTPS port.
- ///
- /// The public HTTPS port.
- public int PublicHttpsPort { get; set; } = DefaultHttpsPort;
-
- ///
- /// Gets or sets the HTTP server port number.
- ///
- /// The HTTP server port number.
- public int HttpServerPortNumber { get; set; } = DefaultHttpPort;
-
- ///
- /// Gets or sets the HTTPS server port number.
- ///
- /// The HTTPS server port number.
- public int HttpsPortNumber { get; set; } = DefaultHttpsPort;
-
///
/// Gets or sets a value indicating whether to use HTTPS.
///
@@ -97,118 +64,66 @@ namespace Jellyfin.Networking.Configuration
public bool EnableHttps { get; set; }
///
- /// Gets or sets the public mapped port.
+ /// Gets or sets a value indicating whether the server should force connections over HTTPS.
///
- /// The public mapped port.
- public int PublicPort { get; set; } = DefaultHttpPort;
+ public bool RequireHttps { get; set; }
///
- /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.
+ /// Gets or sets the filesystem path of an X.509 certificate to use for SSL.
///
- public bool UPnPCreateHttpPortMap { get; set; }
+ public string CertificatePath { get; set; } = string.Empty;
///
- /// Gets or sets the UDPPortRange.
+ /// Gets or sets the password required to access the X.509 certificate data in the file specified by .
///
- public string UDPPortRange { get; set; } = string.Empty;
+ public string CertificatePassword { get; set; } = string.Empty;
///
- /// Gets or sets a value indicating whether gets or sets IPV6 capability.
+ /// Gets or sets the internal HTTP server port.
///
- public bool EnableIPV6 { get; set; }
+ /// The HTTP server port.
+ public int InternalHttpPort { get; set; } = DefaultHttpPort;
///
- /// Gets or sets a value indicating whether gets or sets IPV4 capability.
+ /// Gets or sets the internal HTTPS server port.
///
- public bool EnableIPV4 { get; set; } = true;
+ /// The HTTPS server port.
+ public int InternalHttpsPort { get; set; } = DefaultHttpsPort;
///
- /// Gets or sets a value indicating whether detailed SSDP logs are sent to the console/log.
- /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to have any effect.
+ /// Gets or sets the public HTTP port.
///
- public bool EnableSSDPTracing { get; set; }
+ /// The public HTTP port.
+ public int PublicHttpPort { get; set; } = DefaultHttpPort;
///
- /// Gets or sets the SSDPTracingFilter
- /// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log.
- /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work.
+ /// Gets or sets the public HTTPS port.
///
- public string SSDPTracingFilter { get; set; } = string.Empty;
-
- ///
- /// Gets or sets the number of times SSDP UDP messages are sent.
- ///
- public int UDPSendCount { get; set; } = 2;
-
- ///
- /// Gets or sets the delay between each groups of SSDP messages (in ms).
- ///
- public int UDPSendDelay { get; set; } = 100;
-
- ///
- /// Gets or sets a value indicating whether address names that match should be Ignore for the purposes of binding.
- ///
- public bool IgnoreVirtualInterfaces { get; set; } = true;
-
- ///
- /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. .
- ///
- public string VirtualInterfaceNames { get; set; } = "vEthernet*";
-
- ///
- /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor.
- ///
- public int GatewayMonitorPeriod { get; set; } = 60;
-
- ///
- /// Gets a value indicating whether multi-socket binding is available.
- ///
- public bool EnableMultiSocketBinding { get; } = true;
-
- ///
- /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network.
- /// Depending on the address range implemented ULA ranges might not be used.
- ///
- public bool TrustAllIP6Interfaces { get; set; }
-
- ///
- /// Gets or sets the ports that HDHomerun uses.
- ///
- public string HDHomerunPortRange { get; set; } = string.Empty;
-
- ///
- /// Gets or sets the PublishedServerUriBySubnet
- /// Gets or sets PublishedServerUri to advertise for specific subnets.
- ///
- public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty();
-
- ///
- /// Gets or sets a value indicating whether Autodiscovery tracing is enabled.
- ///
- public bool AutoDiscoveryTracing { get; set; }
+ /// The public HTTPS port.
+ public int PublicHttpsPort { get; set; } = DefaultHttpsPort;
///
/// Gets or sets a value indicating whether Autodiscovery is enabled.
///
public bool AutoDiscovery { get; set; } = true;
- ///
- /// Gets or sets the filter for remote IP connectivity. Used in conjunction with .
- ///
- public string[] RemoteIPFilter { get; set; } = Array.Empty();
-
- ///
- /// Gets or sets a value indicating whether contains a blacklist or a whitelist. Default is a whitelist.
- ///
- public bool IsRemoteIPFilterBlacklist { get; set; }
-
///
/// Gets or sets a value indicating whether to enable automatic port forwarding.
///
public bool EnableUPnP { get; set; }
///
- /// Gets or sets a value indicating whether access outside of the LAN is permitted.
+ /// Gets or sets a value indicating whether IPv6 is enabled.
+ ///
+ public bool EnableIPv4 { get; set; } = true;
+
+ ///
+ /// Gets or sets a value indicating whether IPv6 is enabled.
+ ///
+ public bool EnableIPv6 { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether access from outside of the LAN is permitted.
///
public bool EnableRemoteAccess { get; set; } = true;
@@ -223,13 +138,39 @@ namespace Jellyfin.Networking.Configuration
public string[] LocalNetworkAddresses { get; set; } = Array.Empty();
///
- /// Gets or sets the known proxies. If the proxy is a network, it's added to the KnownNetworks.
+ /// Gets or sets the known proxies.
///
public string[] KnownProxies { get; set; } = Array.Empty();
+ ///
+ /// Gets or sets a value indicating whether address names that match should be ignored for the purposes of binding.
+ ///
+ public bool IgnoreVirtualInterfaces { get; set; } = true;
+
+ ///
+ /// Gets or sets a value indicating the interface name prefixes that should be ignored. The list can be comma separated and values are case-insensitive. .
+ ///
+ public string[] VirtualInterfaceNames { get; set; } = new string[] { "veth" };
+
///
/// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests.
///
public bool EnablePublishedServerUriByRequest { get; set; } = false;
+
+ ///
+ /// Gets or sets the PublishedServerUriBySubnet
+ /// Gets or sets PublishedServerUri to advertise for specific subnets.
+ ///
+ public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty();
+
+ ///
+ /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with .
+ ///
+ public string[] RemoteIPFilter { get; set; } = Array.Empty();
+
+ ///
+ /// Gets or sets a value indicating whether contains a blacklist or a whitelist. Default is a whitelist.
+ ///
+ public bool IsRemoteIPFilterBlacklist { get; set; }
}
}
diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs
index 8cbe398b07..3ba6bb8fcb 100644
--- a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs
+++ b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs
@@ -14,7 +14,7 @@ namespace Jellyfin.Networking.Configuration
/// The .
public static NetworkConfiguration GetNetworkConfiguration(this IConfigurationManager config)
{
- return config.GetConfiguration("network");
+ return config.GetConfiguration(NetworkConfigurationStore.StoreKey);
}
}
}
diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs
index afb0538205..c80038e7d0 100644
--- a/Jellyfin.Networking/Manager/NetworkManager.cs
+++ b/Jellyfin.Networking/Manager/NetworkManager.cs
@@ -1,57 +1,44 @@
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 MediaBrowser.Model.Net;
using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Networking.Manager
{
///
/// Class to take care of network interface management.
- /// Note: The normal collection methods and properties will not work with Collection{IPObject}. .
///
public class NetworkManager : INetworkManager, IDisposable
{
- ///
- /// Contains the description of the interface along with its index.
- ///
- private readonly Dictionary _interfaceNames;
-
///
/// Threading lock for network properties.
///
- private readonly object _intLock = new object();
-
- ///
- /// List of all interface addresses and masks.
- ///
- private readonly Collection _interfaceAddresses;
-
- ///
- /// List of all interface MAC addresses.
- ///
- private readonly List _macAddresses;
+ private readonly object _initLock;
private readonly ILogger _logger;
private readonly IConfigurationManager _configurationManager;
- private readonly object _eventFireLock;
+ private readonly object _networkEventLock;
///
- /// Holds the bind address overrides.
+ /// Holds the published server URLs and the IPs to use them on.
///
- private readonly Dictionary _publishedServerUrls;
+ private IReadOnlyDictionary _publishedServerUrls;
+
+ private IReadOnlyList _remoteAddressFilter;
///
/// Used to stop "event-racing conditions".
@@ -59,35 +46,25 @@ namespace Jellyfin.Networking.Manager
private bool _eventfire;
///
- /// Unfiltered user defined LAN subnets. ()
+ /// List of all interface MAC addresses.
+ ///
+ private IReadOnlyList _macAddresses;
+
+ ///
+ /// Dictionary containing interface addresses and their subnets.
+ ///
+ private IReadOnlyList _interfaces;
+
+ ///
+ /// Unfiltered user defined LAN subnets ()
/// or internal interface network subnets if undefined by user.
///
- private Collection _lanSubnets;
+ private IReadOnlyList _lanSubnets;
///
/// User defined list of subnets to excluded from the LAN.
///
- private Collection _excludedSubnets;
-
- ///
- /// List of interface addresses to bind the WS.
- ///
- private Collection _bindAddresses;
-
- ///
- /// List of interface addresses to exclude from bind.
- ///
- private Collection _bindExclusions;
-
- ///
- /// Caches list of all internal filtered interface addresses and masks.
- ///
- private Collection _internalInterfaces;
-
- ///
- /// Flag set when no custom LAN has been defined in the configuration.
- ///
- private bool _usingPrivateAddresses;
+ private IReadOnlyList _excludedSubnets;
///
/// True if this object is disposed.
@@ -102,14 +79,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 logger)
{
- _logger = logger ?? throw new ArgumentNullException(nameof(logger));
- _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager));
+ ArgumentNullException.ThrowIfNull(logger);
+ ArgumentNullException.ThrowIfNull(configurationManager);
- _interfaceAddresses = new Collection();
+ _logger = logger;
+ _configurationManager = configurationManager;
+ _initLock = new();
+ _interfaces = new List();
_macAddresses = new List();
- _interfaceNames = new Dictionary();
- _publishedServerUrls = new Dictionary();
- _eventFireLock = new object();
+ _publishedServerUrls = new Dictionary();
+ _networkEventLock = new object();
+ _remoteAddressFilter = new List();
UpdateSettings(_configurationManager.GetNetworkConfiguration());
@@ -131,46 +111,24 @@ namespace Jellyfin.Networking.Manager
public static string MockNetworkSettings { get; set; } = string.Empty;
///
- /// Gets or sets a value indicating whether IP6 is enabled.
+ /// Gets a value indicating whether IP4 is enabled.
///
- public bool IsIP6Enabled { get; set; }
+ public bool IsIPv4Enabled => _configurationManager.GetNetworkConfiguration().EnableIPv4;
///
- /// Gets or sets a value indicating whether IP4 is enabled.
+ /// Gets a value indicating whether IP6 is enabled.
///
- public bool IsIP4Enabled { get; set; }
-
- ///
- public Collection RemoteAddressFilter { get; private set; }
+ public bool IsIPv6Enabled => _configurationManager.GetNetworkConfiguration().EnableIPv6;
///
/// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
///
- public bool TrustAllIP6Interfaces { get; internal set; }
+ public bool TrustAllIPv6Interfaces { get; private set; }
///
/// Gets the Published server override list.
///
- public Dictionary PublishedServerUrls => _publishedServerUrls;
-
- ///
- /// Creates a new network collection.
- ///
- /// Items to assign the collection, or null.
- /// The collection created.
- public static Collection CreateCollection(IEnumerable? source = null)
- {
- var result = new Collection();
- if (source is not null)
- {
- foreach (var item in source)
- {
- result.AddItem(item, false);
- }
- }
-
- return result;
- }
+ public IReadOnlyDictionary PublishedServerUrls => _publishedServerUrls;
///
public void Dispose()
@@ -179,407 +137,385 @@ namespace Jellyfin.Networking.Manager
GC.SuppressFinalize(this);
}
- ///
- public IReadOnlyCollection GetMacAddresses()
+ ///
+ /// Handler for network change events.
+ ///
+ /// Sender.
+ /// A containing network availability information.
+ private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e)
{
- // Populated in construction - so always has values.
- return _macAddresses;
+ _logger.LogDebug("Network availability changed.");
+ HandleNetworkChange();
}
- ///
- public bool IsGatewayInterface(IPObject? addressObj)
+ ///
+ /// Handler for network change events.
+ ///
+ /// Sender.
+ /// An .
+ 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();
}
- ///
- public bool IsGatewayInterface(IPAddress? addressObj)
+ ///
+ /// Triggers our event, and re-loads interface information.
+ ///
+ private void HandleNetworkChange()
{
- return _internalInterfaces.Any(i => i.Address.Equals(addressObj ?? IPAddress.None) && i.Tag < 0);
- }
-
- ///
- public Collection GetLoopbacks()
- {
- Collection nc = new Collection();
- if (IsIP4Enabled)
+ lock (_networkEventLock)
{
- nc.AddItem(IPAddress.Loopback);
+ 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();
+ }
}
+ }
- if (IsIP6Enabled)
+ ///
+ /// Waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession.
+ ///
+ private void OnNetworkChange()
+ {
+ try
{
- nc.AddItem(IPAddress.IPv6Loopback);
+ Thread.Sleep(2000);
+ var networkConfig = _configurationManager.GetNetworkConfiguration();
+ if (IsIPv6Enabled && !Socket.OSSupportsIPv6)
+ {
+ UpdateSettings(networkConfig);
+ }
+ else
+ {
+ InitialiseInterfaces();
+ InitialiseLan(networkConfig);
+ EnforceBindSettings(networkConfig);
+ }
+
+ NetworkChanged?.Invoke(this, EventArgs.Empty);
}
-
- return nc;
- }
-
- ///
- public bool IsExcluded(IPAddress ip)
- {
- return _excludedSubnets.ContainsAddress(ip);
- }
-
- ///
- public bool IsExcluded(EndPoint ip)
- {
- return ip is not null && IsExcluded(((IPEndPoint)ip).Address);
- }
-
- ///
- public Collection CreateIPCollection(string[] values, bool negated = false)
- {
- Collection col = new Collection();
- if (values is null)
+ finally
{
- return col;
+ _eventfire = false;
}
+ }
- for (int a = 0; a < values.Length; a++)
+ ///
+ /// 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.
+ ///
+ private void InitialiseInterfaces()
+ {
+ lock (_initLock)
{
- string v = values[a].Trim();
+ _logger.LogDebug("Refreshing interfaces.");
+
+ var interfaces = new List();
+ var macAddresses = new List();
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)
+ }
+#pragma warning disable CA1031 // Do not catch general exception types
+ catch (Exception ex)
+#pragma warning restore CA1031 // Do not catch general exception types
+ {
+ _logger.LogError(ex, "Error obtaining interfaces.");
+ }
+
+ // If no interfaces are found, fallback to loopback interfaces.
+ if (interfaces.Count == 0)
+ {
+ _logger.LogWarning("No interface information available. Using loopback interface(s).");
+
+ if (IsIPv4Enabled && !IsIPv6Enabled)
{
- AddToCollection(col, v);
+ interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo"));
+ }
+
+ if (!IsIPv4Enabled && IsIPv6Enabled)
+ {
+ interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo"));
}
}
- catch (ArgumentException e)
- {
- _logger.LogWarning(e, "Ignoring LAN value {Value}.", v);
- }
- }
- return col;
+ _logger.LogDebug("Discovered {NumberOfInterfaces} interfaces.", interfaces.Count);
+ _logger.LogDebug("Interfaces addresses: {Addresses}", interfaces.OrderByDescending(s => s.AddressFamily == AddressFamily.InterNetwork).Select(s => s.Address.ToString()));
+
+ _macAddresses = macAddresses;
+ _interfaces = interfaces;
+ }
}
- ///
- public Collection GetAllBindInterfaces(bool individualInterfaces = false)
+ ///
+ /// Initialises internal LAN cache.
+ ///
+ private void InitialiseLan(NetworkConfiguration config)
{
- int count = _bindAddresses.Count;
-
- if (count == 0)
+ lock (_initLock)
{
- if (_bindExclusions.Count > 0)
- {
- // Return all the interfaces except the ones specifically excluded.
- return _interfaceAddresses.Exclude(_bindExclusions, false);
- }
+ _logger.LogDebug("Refreshing LAN information.");
- if (individualInterfaces)
- {
- return new Collection(_interfaceAddresses);
- }
+ // Get configuration options
+ var subnets = config.LocalNetworkSubnets;
- // No bind address and no exclusions, so listen on all interfaces.
- Collection result = new Collection();
+ // If no LAN addresses are specified, all private subnets and Loopback are deemed to be the LAN
+ if (!NetworkExtensions.TryParseToSubnets(subnets, out var lanSubnets, false) || lanSubnets.Count == 0)
+ {
+ _logger.LogDebug("Using LAN interface addresses as user provided no LAN details.");
- 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)
+ var fallbackLanSubnets = new List();
+ if (IsIPv6Enabled)
{
- if (iface.AddressFamily == AddressFamily.InterNetworkV6)
+ fallbackLanSubnets.Add(new IPNetwork(IPAddress.IPv6Loopback, 128)); // RFC 4291 (Loopback)
+ fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("fe80::"), 10)); // RFC 4291 (Site local)
+ fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("fc00::"), 7)); // RFC 4193 (Unique local)
+ }
+
+ if (IsIPv4Enabled)
+ {
+ fallbackLanSubnets.Add(new IPNetwork(IPAddress.Loopback, 8)); // RFC 5735 (Loopback)
+ fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); // RFC 1918 (private)
+ fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("172.16.0.0"), 12)); // RFC 1918 (private)
+ fallbackLanSubnets.Add(new IPNetwork(IPAddress.Parse("192.168.0.0"), 16)); // RFC 1918 (private)
+ }
+
+ _lanSubnets = fallbackLanSubnets;
+ }
+ else
+ {
+ _lanSubnets = lanSubnets;
+ }
+
+ _excludedSubnets = NetworkExtensions.TryParseToSubnets(subnets, out var excludedSubnets, true)
+ ? excludedSubnets
+ : new List();
+
+ _logger.LogInformation("Defined LAN addresses: {0}", _lanSubnets.Select(s => s.Prefix + "/" + s.PrefixLength));
+ _logger.LogInformation("Defined LAN exclusions: {0}", _excludedSubnets.Select(s => s.Prefix + "/" + s.PrefixLength));
+ _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Where(s => !_excludedSubnets.Contains(s)).Select(s => s.Prefix + "/" + s.PrefixLength));
+ }
+ }
+
+ ///
+ /// Enforce bind addresses and exclusions on available interfaces.
+ ///
+ private void EnforceBindSettings(NetworkConfiguration config)
+ {
+ lock (_initLock)
+ {
+ // Respect explicit bind addresses
+ var interfaces = _interfaces.ToList();
+ var localNetworkAddresses = config.LocalNetworkAddresses;
+ if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses[0]))
+ {
+ var bindAddresses = localNetworkAddresses.Select(p => NetworkExtensions.TryParseToSubnet(p, out var network)
+ ? network.Prefix
+ : (interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase))
+ .Select(x => x.Address)
+ .FirstOrDefault() ?? IPAddress.None))
+ .Where(x => x != IPAddress.None)
+ .ToHashSet();
+ interfaces = interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList();
+
+ if (bindAddresses.Contains(IPAddress.Loopback))
+ {
+ interfaces.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo"));
+ }
+
+ if (bindAddresses.Contains(IPAddress.IPv6Loopback))
+ {
+ interfaces.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo"));
+ }
+ }
+
+ // Remove all interfaces matching any virtual machine interface prefix
+ if (config.IgnoreVirtualInterfaces)
+ {
+ // Remove potentially existing * and split config string into prefixes
+ var virtualInterfacePrefixes = config.VirtualInterfaceNames
+ .Select(i => i.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase));
+
+ // Check all interfaces for matches against the prefixes and remove them
+ if (_interfaces.Count > 0)
+ {
+ foreach (var virtualInterfacePrefix in virtualInterfacePrefixes)
{
- result.AddItem(iface.Address);
+ interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCase));
}
}
}
- return result;
- }
-
- // Remove any excluded bind interfaces.
- return _bindAddresses.Exclude(_bindExclusions, false);
- }
-
- ///
- public string GetBindInterface(string source, out int? port)
- {
- if (IPHost.TryParse(source, out IPHost host))
- {
- return GetBindInterface(host, out port);
- }
-
- return GetBindInterface(IPHost.None, out port);
- }
-
- ///
- public string GetBindInterface(IPAddress source, out int? port)
- {
- return GetBindInterface(new IPNetAddress(source), out port);
- }
-
- ///
- public string GetBindInterface(HttpRequest source, out int? port)
- {
- string result;
-
- if (source is not null && IPHost.TryParse(source.Host.Host, out IPHost host))
- {
- result = GetBindInterface(host, out port);
- port ??= source.Host.Port;
- }
- else
- {
- result = GetBindInterface(IPNetAddress.None, out port);
- port ??= source?.Host.Port;
- }
-
- return result;
- }
-
- ///
- public string GetBindInterface(IPObject source, out int? port)
- {
- port = null;
- ArgumentNullException.ThrowIfNull(source);
-
- // Do we have a source?
- bool haveSource = !source.Address.Equals(IPAddress.None);
- bool isExternal = false;
-
- if (haveSource)
- {
- if (!IsIP6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6)
+ // Remove all IPv4 interfaces if IPv4 is disabled
+ if (!IsIPv4Enabled)
{
- _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
+ interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork);
}
- if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork)
+ // Remove all IPv6 interfaces if IPv6 is disabled
+ if (!IsIPv6Enabled)
{
- _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
+ interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6);
}
- isExternal = !IsInLocalNetwork(source);
+ _logger.LogInformation("Using bind addresses: {0}", interfaces.OrderByDescending(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.Address));
+ _interfaces = interfaces;
+ }
+ }
- if (MatchesPublishedServerUrl(source, isExternal, out string res, out port))
+ ///
+ /// Initialises the remote address values.
+ ///
+ private void InitialiseRemote(NetworkConfiguration config)
+ {
+ lock (_initLock)
+ {
+ // Parse config values into filter collection
+ var remoteIPFilter = config.RemoteIPFilter;
+ if (remoteIPFilter.Any() && !string.IsNullOrWhiteSpace(remoteIPFilter.First()))
{
- _logger.LogDebug("{Source}: Using BindAddress {Address}:{Port}", source, res, port);
- return res;
- }
- }
-
- _logger.LogDebug("GetBindInterface: Source: {HaveSource}, External: {IsExternal}:", haveSource, isExternal);
-
- // No preference given, so move on to bind addresses.
- if (MatchesBindInterface(source, isExternal, out string result))
- {
- return result;
- }
-
- if (isExternal && MatchesExternalInterface(source, out result))
- {
- return result;
- }
-
- // Get the first LAN interface address that isn't a loopback.
- var interfaces = CreateCollection(
- _interfaceAddresses
- .Exclude(_bindExclusions, false)
- .Where(IsInLocalNetwork)
- .OrderBy(p => p.Tag));
-
- if (interfaces.Count > 0)
- {
- if (haveSource)
- {
- foreach (var intf in interfaces)
+ // Parse all IPs with netmask to a subnet
+ var remoteAddressFilter = new List();
+ var remoteFilteredSubnets = remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase)).ToArray();
+ if (NetworkExtensions.TryParseToSubnets(remoteFilteredSubnets, out var remoteAddressFilterResult, false))
{
- if (intf.Address.Equals(source.Address))
+ remoteAddressFilter = remoteAddressFilterResult.ToList();
+ }
+
+ // Parse everything else as an IP and construct subnet with a single IP
+ var remoteFilteredIPs = remoteIPFilter.Where(x => !x.Contains('/', StringComparison.OrdinalIgnoreCase));
+ foreach (var ip in remoteFilteredIPs)
+ {
+ if (IPAddress.TryParse(ip, out var ipp))
{
- result = FormatIP6String(intf.Address);
- _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface. {Result}", source, result);
- return result;
+ remoteAddressFilter.Add(new IPNetwork(ipp, ipp.AddressFamily == AddressFamily.InterNetwork ? 32 : 128));
}
}
- // 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)
+ _remoteAddressFilter = remoteAddressFilter;
+ }
+ }
+ }
+
+ ///
+ /// Parses the user defined overrides into the dictionary object.
+ /// Overrides are the equivalent of localised publishedServerUrl, enabling
+ /// different addresses to be advertised over different subnets.
+ /// format is subnet=ipaddress|host|uri
+ /// when subnet = 0.0.0.0, any external address matches.
+ ///
+ private void InitialiseOverrides(NetworkConfiguration config)
+ {
+ lock (_initLock)
+ {
+ var publishedServerUrls = new Dictionary();
+ var overrides = config.PublishedServerUriBySubnet;
+
+ foreach (var entry in overrides)
+ {
+ var parts = entry.Split('=');
+ if (parts.Length != 2)
{
- if (intf.Contains(source))
+ _logger.LogError("Unable to parse bind override: {Entry}", entry);
+ return;
+ }
+
+ var replacement = parts[1].Trim();
+ var identifier = parts[0];
+ if (string.Equals(identifier, "all", StringComparison.OrdinalIgnoreCase))
+ {
+ 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)
{
- result = FormatIP6String(intf.Address);
- _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result);
- return result;
+ var lanPrefix = lan.Prefix;
+ publishedServerUrls[new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength))] = replacement;
}
}
- }
-
- result = FormatIP6String(interfaces.First().Address);
- _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result);
- return result;
- }
-
- // There isn't any others, so we'll use the loopback.
- result = IsIP6Enabled ? "::1" : "127.0.0.1";
- _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result);
- return result;
- }
-
- ///
- public Collection GetInternalBindAddresses()
- {
- int count = _bindAddresses.Count;
-
- if (count == 0)
- {
- if (_bindExclusions.Count > 0)
- {
- // Return all the internal interfaces except the ones excluded.
- return CreateCollection(_internalInterfaces.Where(p => !_bindExclusions.ContainsAddress(p)));
- }
-
- // No bind address, so return all internal interfaces.
- return CreateCollection(_internalInterfaces);
- }
-
- return new Collection(_bindAddresses.Where(a => IsInLocalNetwork(a)).ToArray());
- }
-
- ///
- public bool IsInLocalNetwork(IPObject address)
- {
- return IsInLocalNetwork(address.Address);
- }
-
- ///
- public bool IsInLocalNetwork(string address)
- {
- return IPHost.TryParse(address, out IPHost ipHost) && IsInLocalNetwork(ipHost);
- }
-
- ///
- public bool IsInLocalNetwork(IPAddress address)
- {
- ArgumentNullException.ThrowIfNull(address);
-
- if (address.Equals(IPAddress.None))
- {
- return false;
- }
-
- // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
- if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
- {
- return true;
- }
-
- // As private addresses can be redefined by Configuration.LocalNetworkAddresses
- return IPAddress.IsLoopback(address) || (_lanSubnets.ContainsAddress(address) && !_excludedSubnets.ContainsAddress(address));
- }
-
- ///
- public bool IsPrivateAddressRange(IPObject address)
- {
- ArgumentNullException.ThrowIfNull(address);
-
- // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
- if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
- {
- return true;
- }
-
- return address.IsPrivateAddressRange();
- }
-
- ///
- public bool IsExcludedInterface(IPAddress address)
- {
- return _bindExclusions.ContainsAddress(address);
- }
-
- ///
- public Collection GetFilteredLANSubnets(Collection? filter = null)
- {
- if (filter is null)
- {
- return _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks();
- }
-
- return _lanSubnets.Exclude(filter, true);
- }
-
- ///
- public bool IsValidInterfaceAddress(IPAddress address)
- {
- return _interfaceAddresses.ContainsAddress(address);
- }
-
- ///
- public bool TryParseInterface(string token, out Collection? result)
- {
- result = null;
- if (string.IsNullOrEmpty(token))
- {
- return false;
- }
-
- if (_interfaceNames is not null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index))
- {
- result = new Collection();
-
- _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token);
-
- // Replace interface tags with the interface IP's.
- foreach (IPNetAddress iface in _interfaceAddresses)
- {
- if (Math.Abs(iface.Tag) == index
- && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
- || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
+ else if (NetworkExtensions.TryParseToSubnet(identifier, out var result) && result is not null)
{
- result.AddItem(iface, false);
+ var data = new IPData(result.Prefix, result);
+ publishedServerUrls[data] = replacement;
+ }
+ else if (TryParseInterface(identifier, out var ifaces))
+ {
+ foreach (var iface in ifaces)
+ {
+ publishedServerUrls[iface] = replacement;
+ }
+ }
+ else
+ {
+ _logger.LogError("Unable to parse bind override: {Entry}", entry);
}
}
- return true;
+ _publishedServerUrls = publishedServerUrls;
}
-
- return false;
}
- ///
- public bool HasRemoteAccess(IPAddress remoteIp)
+ private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt)
{
- var config = _configurationManager.GetNetworkConfiguration();
- if (config.EnableRemoteAccess)
+ if (evt.Key.Equals(NetworkConfigurationStore.StoreKey, 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;
- }
+ UpdateSettings((NetworkConfiguration)evt.NewConfiguration);
}
- else if (!IsInLocalNetwork(remoteIp))
- {
- // Remote not enabled. So everyone should be LAN.
- return false;
- }
-
- return true;
}
///
@@ -588,19 +524,13 @@ namespace Jellyfin.Networking.Manager
/// The to use.
public void UpdateSettings(object configuration)
{
- NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration));
+ ArgumentNullException.ThrowIfNull(configuration);
- IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4;
- IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6;
- HappyEyeballs.HttpClientExtension.UseIPv6 = IsIP6Enabled;
+ var config = (NetworkConfiguration)configuration;
+ HappyEyeballs.HttpClientExtension.UseIPv6 = config.EnableIPv6;
- if (!IsIP6Enabled && !IsIP4Enabled)
- {
- _logger.LogError("IPv4 and IPv6 cannot both be disabled.");
- IsIP4Enabled = true;
- }
-
- TrustAllIP6Interfaces = config.TrustAllIP6Interfaces;
+ InitialiseLan(config);
+ InitialiseRemote(config);
if (string.IsNullOrEmpty(MockNetworkSettings))
{
@@ -610,20 +540,31 @@ namespace Jellyfin.Networking.Manager
{
// Format is ,,: . Set index to -ve to simulate a gateway.
var interfaceList = MockNetworkSettings.Split('|');
+ var interfaces = new List();
foreach (var details in interfaceList)
{
var parts = details.Split(',');
- var address = IPNetAddress.Parse(parts[0]);
- var index = int.Parse(parts[1], CultureInfo.InvariantCulture);
- address.Tag = index;
- _interfaceAddresses.AddItem(address, false);
- _interfaceNames[parts[2]] = Math.Abs(index);
+ if (NetworkExtensions.TryParseToSubnet(parts[0], out var subnet))
+ {
+ var address = subnet.Prefix;
+ var index = int.Parse(parts[1], CultureInfo.InvariantCulture);
+ if (address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ var data = new IPData(address, subnet, parts[2]);
+ data.Index = index;
+ interfaces.Add(data);
+ }
+ }
+ else
+ {
+ _logger.LogWarning("Could not parse mock interface settings: {Part}", details);
+ }
}
+
+ _interfaces = interfaces;
}
- InitialiseLAN(config);
- InitialiseBind(config);
- InitialiseRemote(config);
+ EnforceBindSettings(config);
InitialiseOverrides(config);
}
@@ -646,558 +587,341 @@ namespace Jellyfin.Networking.Manager
}
}
- ///
- /// Tries to identify the string and return an object of that class.
- ///
- /// String to parse.
- /// IPObject to return.
- /// true if the value parsed successfully, false otherwise.
- private static bool TryParse(string addr, out IPObject result)
+ ///
+ public bool TryParseInterface(string intf, [NotNullWhen(true)] out IReadOnlyList? result)
{
- if (!string.IsNullOrEmpty(addr))
+ if (string.IsNullOrEmpty(intf)
+ || _interfaces is null
+ || _interfaces.Count == 0)
{
- // Is it an IP address
- if (IPNetAddress.TryParse(addr, out IPNetAddress nw))
+ result = null;
+ return false;
+ }
+
+ // Match all interfaces starting with names starting with token
+ result = _interfaces
+ .Where(i => i.Name.Equals(intf, StringComparison.OrdinalIgnoreCase)
+ && ((IsIPv4Enabled && i.Address.AddressFamily == AddressFamily.InterNetwork)
+ || (IsIPv6Enabled && i.Address.AddressFamily == AddressFamily.InterNetworkV6)))
+ .OrderBy(x => x.Index)
+ .ToArray();
+ return result.Count > 0;
+ }
+
+ ///
+ public bool HasRemoteAccess(IPAddress remoteIP)
+ {
+ var config = _configurationManager.GetNetworkConfiguration();
+ if (config.EnableRemoteAccess)
+ {
+ // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
+ // If left blank, all remote addresses will be allowed.
+ if (_remoteAddressFilter.Any() && !_lanSubnets.Any(x => x.Contains(remoteIP)))
{
- result = nw;
- return true;
+ // remoteAddressFilter is a whitelist or blacklist.
+ var matches = _remoteAddressFilter.Count(remoteNetwork => remoteNetwork.Contains(remoteIP));
+ if ((!config.IsRemoteIPFilterBlacklist && matches > 0)
+ || (config.IsRemoteIPFilterBlacklist && matches == 0))
+ {
+ return true;
+ }
+
+ return false;
+ }
+ }
+ else if (!_lanSubnets.Any(x => x.Contains(remoteIP)))
+ {
+ // Remote not enabled. So everyone should be LAN.
+ return false;
+ }
+
+ return true;
+ }
+
+ ///
+ public IReadOnlyList GetMacAddresses()
+ {
+ // Populated in construction - so always has values.
+ return _macAddresses;
+ }
+
+ ///
+ public IReadOnlyList GetLoopbacks()
+ {
+ if (!IsIPv4Enabled && !IsIPv6Enabled)
+ {
+ return Array.Empty();
+ }
+
+ var loopbackNetworks = new List();
+ if (IsIPv4Enabled)
+ {
+ loopbackNetworks.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo"));
+ }
+
+ if (IsIPv6Enabled)
+ {
+ loopbackNetworks.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo"));
+ }
+
+ return loopbackNetworks;
+ }
+
+ ///
+ public IReadOnlyList GetAllBindInterfaces(bool individualInterfaces = false)
+ {
+ if (_interfaces.Count != 0)
+ {
+ return _interfaces;
+ }
+
+ // No bind address and no exclusions, so listen on all interfaces.
+ var result = new List();
+
+ if (individualInterfaces)
+ {
+ result.AddRange(_interfaces);
+ return result;
+ }
+
+ if (IsIPv4Enabled && IsIPv6Enabled)
+ {
+ // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any by default
+ result.Add(new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0)));
+ }
+ else if (IsIPv4Enabled)
+ {
+ result.Add(new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0)));
+ }
+ else if (IsIPv6Enabled)
+ {
+ // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too.
+ foreach (var iface in _interfaces)
+ {
+ if (iface.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ result.Add(iface);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ ///
+ public string GetBindAddress(string source, out int? port)
+ {
+ if (!NetworkExtensions.TryParseHost(source, out var addresses, IsIPv4Enabled, IsIPv6Enabled))
+ {
+ addresses = Array.Empty();
+ }
+
+ var result = GetBindAddress(addresses.FirstOrDefault(), out port);
+ return result;
+ }
+
+ ///
+ public string GetBindAddress(HttpRequest source, out int? port)
+ {
+ var result = GetBindAddress(source.Host.Host, out port);
+ port ??= source.Host.Port;
+
+ return result;
+ }
+
+ ///
+ public string GetBindAddress(IPAddress? source, out int? port, bool skipOverrides = false)
+ {
+ port = null;
+
+ string result;
+
+ if (source is not null)
+ {
+ if (IsIPv4Enabled && !IsIPv6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
}
- if (IPHost.TryParse(addr, out IPHost h))
+ if (!IsIPv4Enabled && IsIPv6Enabled && source.AddressFamily == AddressFamily.InterNetwork)
{
- result = h;
+ _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
+ }
+
+ bool isExternal = !_lanSubnets.Any(network => network.Contains(source));
+ _logger.LogDebug("Trying to get bind address for source {Source} - External: {IsExternal}", source, isExternal);
+
+ if (!skipOverrides && MatchesPublishedServerUrl(source, isExternal, out result))
+ {
+ return result;
+ }
+
+ // No preference given, so move on to bind addresses.
+ if (MatchesBindInterface(source, isExternal, out result))
+ {
+ return result;
+ }
+
+ if (isExternal && MatchesExternalInterface(source, out result))
+ {
+ return result;
+ }
+ }
+
+ // Get the first LAN interface address that's not excluded and not a loopback address.
+ // Get all available interfaces, prefer local interfaces
+ var availableInterfaces = _interfaces.Where(x => !IPAddress.IsLoopback(x.Address))
+ .OrderByDescending(x => IsInLocalNetwork(x.Address))
+ .ThenBy(x => x.Index)
+ .ToList();
+
+ if (availableInterfaces.Count == 0)
+ {
+ // There isn't any others, so we'll use the loopback.
+ result = IsIPv4Enabled && !IsIPv6Enabled ? "127.0.0.1" : "::1";
+ _logger.LogWarning("{Source}: Only loopback {Result} returned, using that as bind address.", source, result);
+ return result;
+ }
+
+ // If no source address is given, use the preferred (first) interface
+ if (source is null)
+ {
+ result = NetworkExtensions.FormatIPString(availableInterfaces.First().Address);
+ _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result);
+ return result;
+ }
+
+ // Does the request originate in one of the interface subnets?
+ // (For systems with multiple internal network cards, and multiple subnets)
+ foreach (var intf in availableInterfaces)
+ {
+ if (intf.Subnet.Contains(source))
+ {
+ result = NetworkExtensions.FormatIPString(intf.Address);
+ _logger.LogDebug("{Source}: Found interface with matching subnet, using it as bind address: {Result}", source, result);
+ return result;
+ }
+ }
+
+ // Fallback to first available interface
+ result = NetworkExtensions.FormatIPString(availableInterfaces[0].Address);
+ _logger.LogDebug("{Source}: No matching interfaces found, using preferred interface as bind address: {Result}", source, result);
+ return result;
+ }
+
+ ///
+ public IReadOnlyList GetInternalBindAddresses()
+ {
+ // Select all local bind addresses
+ return _interfaces.Where(x => IsInLocalNetwork(x.Address))
+ .OrderBy(x => x.Index)
+ .ToList();
+ }
+
+ ///
+ 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)));
+ }
+
+ if (NetworkExtensions.TryParseHost(address, out var addresses, IsIPv4Enabled, IsIPv6Enabled))
+ {
+ foreach (var ept in addresses)
+ {
+ if (IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept))))
+ {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ ///
+ public bool IsInLocalNetwork(IPAddress address)
+ {
+ ArgumentNullException.ThrowIfNull(address);
+
+ // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
+ if ((TrustAllIPv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
+ || address.Equals(IPAddress.Loopback)
+ || address.Equals(IPAddress.IPv6Loopback))
+ {
+ return true;
+ }
+
+ // As private addresses can be redefined by Configuration.LocalNetworkAddresses
+ return CheckIfLanAndNotExcluded(address);
+ }
+
+ private bool CheckIfLanAndNotExcluded(IPAddress address)
+ {
+ foreach (var lanSubnet in _lanSubnets)
+ {
+ if (lanSubnet.Contains(address))
+ {
+ foreach (var excludedSubnet in _excludedSubnets)
+ {
+ if (excludedSubnet.Contains(address))
+ {
+ return false;
+ }
+ }
+
return true;
}
}
- result = IPNetAddress.None;
return false;
}
///
- /// Converts an IPAddress into a string.
- /// Ipv6 addresses are returned in [ ], with their scope removed.
- ///
- /// Address to convert.
- /// URI safe conversion of the address.
- private static string FormatIP6String(IPAddress address)
- {
- var str = address.ToString();
- if (address.AddressFamily == AddressFamily.InterNetworkV6)
- {
- int i = str.IndexOf("%", StringComparison.OrdinalIgnoreCase);
- if (i != -1)
- {
- str = str.Substring(0, i);
- }
-
- return $"[{str}]";
- }
-
- return str;
- }
-
- private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt)
- {
- if (evt.Key.Equals(NetworkConfigurationStore.StoreKey, StringComparison.Ordinal))
- {
- UpdateSettings((NetworkConfiguration)evt.NewConfiguration);
- }
- }
-
- ///
- /// Checks the string to see if it matches any interface names.
- ///
- /// String to check.
- /// Interface index numbers that match.
- /// true if an interface name matches the token, False otherwise.
- private bool TryGetInterfaces(string token, [NotNullWhen(true)] out List? index)
- {
- index = null;
-
- // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
- // Null check required here for automated testing.
- if (_interfaceNames is not null && token.Length > 1)
- {
- bool partial = token[^1] == '*';
- if (partial)
- {
- token = token[..^1];
- }
-
- foreach ((string interfc, int interfcIndex) in _interfaceNames)
- {
- if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase))
- || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture)))
- {
- index ??= new List();
- index.Add(interfcIndex);
- }
- }
- }
-
- return index is not null;
- }
-
- ///
- /// Parses a string and adds it into the collection, replacing any interface references.
- ///
- /// Collection.
- /// String value to parse.
- private void AddToCollection(Collection col, string token)
- {
- // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
- // Null check required here for automated testing.
- if (TryGetInterfaces(token, out var indices))
- {
- _logger.LogInformation("Interface {Token} used in settings. Using its interface addresses.", token);
-
- // Replace all the interface tags with the interface IP's.
- foreach (IPNetAddress iface in _interfaceAddresses)
- {
- if (indices.Contains(Math.Abs(iface.Tag))
- && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
- || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
- {
- col.AddItem(iface);
- }
- }
- }
- else if (TryParse(token, out IPObject obj))
- {
- // Expand if the ip address is "any".
- if ((obj.Address.Equals(IPAddress.Any) && IsIP4Enabled)
- || (obj.Address.Equals(IPAddress.IPv6Any) && IsIP6Enabled))
- {
- foreach (IPNetAddress iface in _interfaceAddresses)
- {
- if (obj.AddressFamily == iface.AddressFamily)
- {
- col.AddItem(iface);
- }
- }
- }
- else if (!IsIP6Enabled)
- {
- // Remove IP6 addresses from multi-homed IPHosts.
- obj.Remove(AddressFamily.InterNetworkV6);
- if (!obj.IsIP6())
- {
- col.AddItem(obj);
- }
- }
- else if (!IsIP4Enabled)
- {
- // Remove IP4 addresses from multi-homed IPHosts.
- obj.Remove(AddressFamily.InterNetwork);
- if (obj.IsIP6())
- {
- col.AddItem(obj);
- }
- }
- else
- {
- col.AddItem(obj);
- }
- }
- else
- {
- _logger.LogDebug("Invalid or unknown object {Token}.", token);
- }
- }
-
- ///
- /// Handler for network change events.
- ///
- /// Sender.
- /// A containing network availability information.
- private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e)
- {
- _logger.LogDebug("Network availability changed.");
- OnNetworkChanged();
- }
-
- ///
- /// Handler for network change events.
- ///
- /// Sender.
- /// An .
- private void OnNetworkAddressChanged(object? sender, EventArgs e)
- {
- _logger.LogDebug("Network address change detected.");
- OnNetworkChanged();
- }
-
- ///
- /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession.
- ///
- /// A representing the asynchronous operation.
- private async Task OnNetworkChangeAsync()
- {
- try
- {
- await Task.Delay(2000).ConfigureAwait(false);
-
- var config = _configurationManager.GetNetworkConfiguration();
- // Have we lost IPv6 capability?
- if (IsIP6Enabled && !Socket.OSSupportsIPv6)
- {
- UpdateSettings(config);
- }
- else
- {
- InitialiseInterfaces();
- // Recalculate LAN caches.
- InitialiseLAN(config);
- }
-
- NetworkChanged?.Invoke(this, EventArgs.Empty);
- }
- finally
- {
- _eventfire = false;
- }
- }
-
- ///
- /// Triggers our event, and re-loads interface information.
- ///
- private void OnNetworkChanged()
- {
- lock (_eventFireLock)
- {
- if (!_eventfire)
- {
- _logger.LogDebug("Network Address Change Event.");
- // As network events tend to fire one after the other only fire once every second.
- _eventfire = true;
- OnNetworkChangeAsync().GetAwaiter().GetResult();
- }
- }
- }
-
- ///
- /// Parses the user defined overrides into the dictionary object.
- /// Overrides are the equivalent of localised publishedServerUrl, enabling
- /// different addresses to be advertised over different subnets.
- /// format is subnet=ipaddress|host|uri
- /// when subnet = 0.0.0.0, any external address matches.
- ///
- private void InitialiseOverrides(NetworkConfiguration config)
- {
- lock (_intLock)
- {
- _publishedServerUrls.Clear();
- string[] overrides = config.PublishedServerUriBySubnet;
- if (overrides is null)
- {
- return;
- }
-
- foreach (var entry in overrides)
- {
- var parts = entry.Split('=');
- if (parts.Length != 2)
- {
- _logger.LogError("Unable to parse bind override: {Entry}", entry);
- }
- else
- {
- var replacement = parts[1].Trim();
- if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase))
- {
- _publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement;
- }
- else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase))
- {
- _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement;
- }
- else if (TryParseInterface(parts[0], out Collection? addresses) && addresses 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]);
- }
- }
- }
- }
- }
-
- ///
- /// Initialises the network bind addresses.
- ///
- 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)
- {
- // 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;
- }
- }
-
- // Read and parse bind addresses and exclusions, removing ones that don't exist.
- _bindAddresses = CreateIPCollection(lanAddresses).ThatAreContainedInNetworks(_interfaceAddresses);
- _bindExclusions = CreateIPCollection(lanAddresses, true).ThatAreContainedInNetworks(_interfaceAddresses);
- _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString());
- _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString());
- }
- }
-
- ///
- /// Initialises the remote address values.
- ///
- private void InitialiseRemote(NetworkConfiguration config)
- {
- lock (_intLock)
- {
- RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter);
- }
- }
-
- ///
- /// Initialises internal LAN cache settings.
- ///
- private void InitialiseLAN(NetworkConfiguration config)
- {
- lock (_intLock)
- {
- _logger.LogDebug("Refreshing LAN information.");
-
- // Get configuration options.
- string[] subnets = config.LocalNetworkSubnets;
-
- // Create lists from user settings.
-
- _lanSubnets = CreateIPCollection(subnets);
- _excludedSubnets = CreateIPCollection(subnets, true).AsNetworks();
-
- // If no LAN addresses are specified - all private subnets are deemed to be the LAN
- _usingPrivateAddresses = _lanSubnets.Count == 0;
-
- // NOTE: The order of the commands generating the collection in this statement matters.
- // Altering the order will cause the collections to be created incorrectly.
- if (_usingPrivateAddresses)
- {
- _logger.LogDebug("Using LAN interface addresses as user provided no LAN details.");
- // Internal interfaces must be private and not excluded.
- _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i)));
-
- // Subnets are the same as the calculated internal interface.
- _lanSubnets = new Collection();
-
- if (IsIP6Enabled)
- {
- _lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA
- _lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local
- }
-
- if (IsIP4Enabled)
- {
- _lanSubnets.AddItem(IPNetAddress.Parse("10.0.0.0/8"));
- _lanSubnets.AddItem(IPNetAddress.Parse("172.16.0.0/12"));
- _lanSubnets.AddItem(IPNetAddress.Parse("192.168.0.0/16"));
- }
- }
- else
- {
- // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet.
- _internalInterfaces = CreateCollection(_interfaceAddresses.Where(IsInLocalNetwork));
- }
-
- _logger.LogInformation("Defined LAN addresses: {0}", _lanSubnets.AsString());
- _logger.LogInformation("Defined LAN exclusions: {0}", _excludedSubnets.AsString());
- _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks().AsString());
- }
- }
-
- ///
- /// 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.
- ///
- private void InitialiseInterfaces()
- {
- lock (_intLock)
- {
- _logger.LogDebug("Refreshing interfaces.");
-
- _interfaceNames.Clear();
- _interfaceAddresses.Clear();
- _macAddresses.Clear();
-
- try
- {
- IEnumerable nics = NetworkInterface.GetAllNetworkInterfaces()
- .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up);
-
- foreach (NetworkInterface adapter in nics)
- {
- try
- {
- IPInterfaceProperties ipProperties = adapter.GetIPProperties();
- PhysicalAddress mac = adapter.GetPhysicalAddress();
-
- // populate mac list
- if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac is not null && mac != PhysicalAddress.None)
- {
- _macAddresses.Add(mac);
- }
-
- // populate interface address list
- foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses)
- {
- if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork)
- {
- IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask))
- {
- // Keep the number of gateways on this interface, along with its index.
- Tag = ipProperties.GetIPv4Properties().Index
- };
-
- int tag = nw.Tag;
- if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback())
- {
- // -ve Tags signify the interface has a gateway.
- nw.Tag *= -1;
- }
-
- _interfaceAddresses.AddItem(nw, false);
-
- // Store interface name so we can use the name in Collections.
- _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
- _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
- }
- else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6)
- {
- IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength)
- {
- // Keep the number of gateways on this interface, along with its index.
- Tag = ipProperties.GetIPv6Properties().Index
- };
-
- int tag = nw.Tag;
- if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback())
- {
- // -ve Tags signify the interface has a gateway.
- nw.Tag *= -1;
- }
-
- _interfaceAddresses.AddItem(nw, false);
-
- // Store interface name so we can use the name in Collections.
- _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
- _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
- }
- }
- }
-#pragma warning disable CA1031 // Do not catch general exception types
- catch (Exception ex)
- {
- // 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.");
- }
-
- // If for some reason we don't have an interface info, resolve our DNS name.
- if (_interfaceAddresses.Count == 0)
- {
- _logger.LogError("No interfaces information available. Resolving DNS name.");
- IPHost host = new IPHost(Dns.GetHostName());
- foreach (var a in host.GetAddresses())
- {
- _interfaceAddresses.AddItem(a);
- }
-
- if (_interfaceAddresses.Count == 0)
- {
- _logger.LogWarning("No interfaces information available. Using loopback.");
- }
- }
-
- if (IsIP4Enabled)
- {
- _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback);
- }
-
- if (IsIP6Enabled)
- {
- _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback);
- }
-
- _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count);
- _logger.LogDebug("Interfaces addresses: {0}", _interfaceAddresses.AsString());
- }
- }
-
- ///
- /// Attempts to match the source against a user defined bind interface.
+ /// Attempts to match the source against the published server URL overrides.
///
/// IP source address to use.
- /// True if the source is in the external subnet.
- /// The published server url that matches the source address.
- /// The resultant port, if one exists.
+ /// True if the source is in an external subnet.
+ /// The published server URL that matches the source address.
/// true if a match is found, false otherwise.
- private bool MatchesPublishedServerUrl(IPObject source, bool isInExternalSubnet, out string bindPreference, out int? port)
+ private bool MatchesPublishedServerUrl(IPAddress source, bool isInExternalSubnet, out string bindPreference)
{
bindPreference = string.Empty;
- port = null;
+ int? port = null;
+
+ var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any)
+ || x.Key.Address.Equals(IPAddress.IPv6Any)
+ || x.Key.Subnet.Contains(source))
+ .DistinctBy(x => x.Key)
+ .OrderBy(x => x.Key.Address.Equals(IPAddress.Any)
+ || x.Key.Address.Equals(IPAddress.IPv6Any))
+ .ToList();
// Check for user override.
- foreach (var addr in _publishedServerUrls)
+ foreach (var data in validPublishedServerUrls)
{
- // Remaining. Match anything.
- if (addr.Key.Address.Equals(IPAddress.Broadcast))
- {
- bindPreference = addr.Value;
- break;
- }
-
- if ((addr.Key.Address.Equals(IPAddress.Any) || addr.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet)
+ if (isInExternalSubnet && (data.Key.Address.Equals(IPAddress.Any) || data.Key.Address.Equals(IPAddress.IPv6Any)))
{
// External.
- bindPreference = addr.Value;
+ bindPreference = data.Value;
break;
}
- if (addr.Key.Contains(source))
+ // Get address interface.
+ var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(x => data.Key.Subnet.Contains(x.Address));
+
+ if (intf?.Address is not null)
{
- // Match ip address.
- bindPreference = addr.Value;
+ // Match IP address.
+ bindPreference = data.Value;
break;
}
}
if (string.IsNullOrEmpty(bindPreference))
{
+ _logger.LogDebug("{Source}: No matching bind address override found", source);
return false;
}
@@ -1212,129 +936,120 @@ namespace Jellyfin.Networking.Manager
}
}
+ if (port is not null)
+ {
+ _logger.LogDebug("{Source}: Matching bind address override found: {Address}:{Port}", source, bindPreference, port);
+ }
+ else
+ {
+ _logger.LogDebug("{Source}: Matching bind address override found: {Address}", source, bindPreference);
+ }
+
return true;
}
///
- /// Attempts to match the source against a user defined bind interface.
+ /// Attempts to match the source against the user defined bind interfaces.
///
/// IP source address to use.
/// True if the source is in the external subnet.
/// The result, if a match is found.
/// true if a match is found, false otherwise.
- private bool MatchesBindInterface(IPObject source, bool isInExternalSubnet, out string result)
+ private bool MatchesBindInterface(IPAddress source, bool isInExternalSubnet, out string result)
{
result = string.Empty;
- var addresses = _bindAddresses.Exclude(_bindExclusions, false);
- int count = addresses.Count;
- 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.
+ return false;
+ }
- IPAddress? defaultGateway = null;
- IPAddress? bindAddress = null;
-
- if (isInExternalSubnet)
+ IPAddress? bindAddress = null;
+ if (isInExternalSubnet)
+ {
+ var externalInterfaces = _interfaces.Where(x => !IsInLocalNetwork(x.Address))
+ .OrderBy(x => x.Index)
+ .ToList();
+ if (externalInterfaces.Count > 0)
{
- // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first.
- foreach (var addr in addresses.OrderBy(p => p.Tag))
- {
- if (defaultGateway is null && !IsInLocalNetwork(addr))
- {
- defaultGateway = addr.Address;
- }
+ // Check to see if any of the external bind interfaces are in the same subnet as the source.
+ // If none exists, this will select the first external interface if there is one.
+ bindAddress = externalInterfaces
+ .OrderByDescending(x => x.Subnet.Contains(source))
+ .ThenBy(x => x.Index)
+ .Select(x => x.Address)
+ .First();
- if (bindAddress is null && addr.Contains(source))
- {
- bindAddress = addr.Address;
- }
+ result = NetworkExtensions.FormatIPString(bindAddress);
+ _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", source, result);
+ return true;
+ }
- if (defaultGateway is not null && bindAddress is not null)
- {
- break;
- }
- }
- }
- else
- {
- // Look for the best internal address.
- bindAddress = addresses
- .Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None)))
- .MinBy(p => p.Tag)?.Address;
- }
+ _logger.LogWarning("{Source}: External request received, no matching external bind address found, trying internal addresses.", source);
+ }
+ else
+ {
+ // Check to see if any of the internal bind interfaces are in the same subnet as the source.
+ // If none exists, this will select the first internal interface if there is one.
+ bindAddress = _interfaces.Where(x => IsInLocalNetwork(x.Address))
+ .OrderByDescending(x => x.Subnet.Contains(source))
+ .ThenBy(x => x.Index)
+ .Select(x => x.Address)
+ .FirstOrDefault();
if (bindAddress is not null)
{
- result = FormatIP6String(bindAddress);
- _logger.LogDebug("{Source}: GetBindInterface: Has source, found a match bind interface subnets. {Result}", source, result);
+ result = NetworkExtensions.FormatIPString(bindAddress);
+ _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {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;
- }
-
- result = FormatIP6String(addresses[0].Address);
- _logger.LogDebug("{Source}: GetBindInterface: Selected first user defined interface. {Result}", source, result);
-
- if (isInExternalSubnet)
- {
- _logger.LogWarning("{Source}: External request received, however, only an internal interface bind found.", source);
- }
-
- return true;
}
return false;
}
///
- /// Attempts to match the source against an external interface.
+ /// Attempts to match the source against external interfaces.
///
/// IP source address to use.
/// The result, if a match is found.
/// true if a match is found, false otherwise.
- private bool MatchesExternalInterface(IPObject source, out string result)
+ private bool MatchesExternalInterface(IPAddress source, out string result)
{
- result = string.Empty;
- // Get the first WAN interface address that isn't a loopback.
- var extResult = _interfaceAddresses
- .Exclude(_bindExclusions, false)
- .Where(p => !IsInLocalNetwork(p))
- .OrderBy(p => p.Tag)
- .ToList();
+ // Get the first external interface address that isn't a loopback.
+ var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address)).OrderBy(x => x.Index).ToArray();
- if (extResult.Any())
+ // No external interface found
+ if (extResult.Length == 0)
{
- // Does the request originate in one of the interface subnets?
- // (For systems with multiple internal network cards, and multiple subnets)
- foreach (var intf in extResult)
- {
- 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 = FormatIP6String(extResult.First().Address);
- _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface. {Result}", source, result);
- return true;
+ result = string.Empty;
+ _logger.LogWarning("{Source}: External request received, but no external interface found. Need to route through internal network.", source);
+ return false;
}
- _logger.LogDebug("{Source}: External request received, but no WAN interface found. Need to route through internal network.", source);
- return false;
+ // Does the request originate in one of the interface subnets?
+ // (For systems with multiple network cards and/or multiple subnets)
+ foreach (var intf in extResult)
+ {
+ if (intf.Subnet.Contains(source))
+ {
+ result = NetworkExtensions.FormatIPString(intf.Address);
+ _logger.LogDebug("{Source}: Found external interface with matching subnet, using it as bind address: {Result}", source, result);
+ return true;
+ }
+ }
+
+ // Fallback to first external interface.
+ result = NetworkExtensions.FormatIPString(extResult.First().Address);
+ _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result);
+ return true;
}
}
}
diff --git a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs
index 463ca7321d..b6af9baec3 100644
--- a/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs
+++ b/Jellyfin.Server/Extensions/ApiApplicationBuilderExtensions.cs
@@ -63,9 +63,9 @@ namespace Jellyfin.Server.Extensions
///
/// The application builder.
/// The updated application builder.
- public static IApplicationBuilder UseIpBasedAccessValidation(this IApplicationBuilder appBuilder)
+ public static IApplicationBuilder UseIPBasedAccessValidation(this IApplicationBuilder appBuilder)
{
- return appBuilder.UseMiddleware();
+ return appBuilder.UseMiddleware();
}
///
diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
index 9867c9e47a..ea3c92011f 100644
--- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
+++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs
@@ -99,7 +99,7 @@ namespace Jellyfin.Server.Extensions
}
///
- /// Extension method for adding the jellyfin API to the service collection.
+ /// Extension method for adding the Jellyfin API to the service collection.
///
/// The service collection.
/// An IEnumerable containing all plugin assemblies with API controllers.
@@ -260,7 +260,7 @@ namespace Jellyfin.Server.Extensions
}
///
- /// Sets up the proxy configuration based on the addresses in .
+ /// Sets up the proxy configuration based on the addresses/subnets in .
///
/// The containing the config settings.
/// The string array to parse.
@@ -269,33 +269,37 @@ 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, address, address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128);
+ 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);
}
}
}
}
- private static void AddIpAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength)
+ private static void AddIPAddress(NetworkConfiguration config, ForwardedHeadersOptions options, IPAddress addr, int prefixLength)
{
- if ((!config.EnableIPV4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPV6 && addr.AddressFamily == AddressFamily.InterNetworkV6))
+ if ((!config.EnableIPv4 && addr.AddressFamily == AddressFamily.InterNetwork) || (!config.EnableIPv6 && addr.AddressFamily == AddressFamily.InterNetworkV6))
{
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/Extensions/WebHostBuilderExtensions.cs b/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs
index 58d3e1b2d9..3cb791b571 100644
--- a/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs
+++ b/Jellyfin.Server/Extensions/WebHostBuilderExtensions.cs
@@ -39,9 +39,9 @@ public static class WebHostBuilderExtensions
var addresses = appHost.NetManager.GetAllBindInterfaces();
bool flagged = false;
- foreach (IPObject netAdd in addresses)
+ foreach (var netAdd in addresses)
{
- logger.LogInformation("Kestrel listening on {Address}", IPAddress.IPv6Any.Equals(netAdd.Address) ? "All Addresses" : netAdd);
+ logger.LogInformation("Kestrel is listening on {Address}", IPAddress.IPv6Any.Equals(netAdd.Address) ? "All IPv6 addresses" : netAdd.Address);
options.Listen(netAdd.Address, appHost.HttpPort);
if (appHost.ListenWithHttps)
{
diff --git a/Jellyfin.Server/Migrations/MigrationRunner.cs b/Jellyfin.Server/Migrations/MigrationRunner.cs
index abfdcd77d5..33c02f41c6 100644
--- a/Jellyfin.Server/Migrations/MigrationRunner.cs
+++ b/Jellyfin.Server/Migrations/MigrationRunner.cs
@@ -22,7 +22,8 @@ namespace Jellyfin.Server.Migrations
private static readonly Type[] _preStartupMigrationTypes =
{
typeof(PreStartupRoutines.CreateNetworkConfiguration),
- typeof(PreStartupRoutines.MigrateMusicBrainzTimeout)
+ typeof(PreStartupRoutines.MigrateMusicBrainzTimeout),
+ typeof(PreStartupRoutines.MigrateNetworkConfiguration)
};
///
diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs
index 5e601ca847..2c2715526f 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();
diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs
new file mode 100644
index 0000000000..3b32e60437
--- /dev/null
+++ b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs
@@ -0,0 +1,195 @@
+using System;
+using System.IO;
+using System.Xml;
+using System.Xml.Serialization;
+using Emby.Server.Implementations;
+using Jellyfin.Networking.Configuration;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Server.Migrations.PreStartupRoutines;
+
+///
+public class MigrateNetworkConfiguration : IMigrationRoutine
+{
+ private readonly ServerApplicationPaths _applicationPaths;
+ private readonly ILogger _logger;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// An instance of .
+ /// An instance of the interface.
+ public MigrateNetworkConfiguration(ServerApplicationPaths applicationPaths, ILoggerFactory loggerFactory)
+ {
+ _applicationPaths = applicationPaths;
+ _logger = loggerFactory.CreateLogger();
+ }
+
+ ///
+ public Guid Id => Guid.Parse("4FB5C950-1991-11EE-9B4B-0800200C9A66");
+
+ ///
+ public string Name => nameof(MigrateNetworkConfiguration);
+
+ ///
+ public bool PerformOnNewInstall => false;
+
+ ///
+ public void Perform()
+ {
+ string path = Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "network.xml");
+ var oldNetworkConfigSerializer = new XmlSerializer(typeof(OldNetworkConfiguration), new XmlRootAttribute("NetworkConfiguration"));
+ using var xmlReader = XmlReader.Create(path);
+ var oldNetworkConfiguration = (OldNetworkConfiguration?)oldNetworkConfigSerializer.Deserialize(xmlReader);
+
+ if (oldNetworkConfiguration is not null)
+ {
+ // Migrate network config values to new config schema
+ var networkConfiguration = new NetworkConfiguration();
+ networkConfiguration.AutoDiscovery = oldNetworkConfiguration.AutoDiscovery;
+ networkConfiguration.BaseUrl = oldNetworkConfiguration.BaseUrl;
+ networkConfiguration.CertificatePassword = oldNetworkConfiguration.CertificatePassword;
+ networkConfiguration.CertificatePath = oldNetworkConfiguration.CertificatePath;
+ networkConfiguration.EnableHttps = oldNetworkConfiguration.EnableHttps;
+ networkConfiguration.EnableIPv4 = oldNetworkConfiguration.EnableIPV4;
+ networkConfiguration.EnableIPv6 = oldNetworkConfiguration.EnableIPV6;
+ networkConfiguration.EnablePublishedServerUriByRequest = oldNetworkConfiguration.EnablePublishedServerUriByRequest;
+ networkConfiguration.EnableRemoteAccess = oldNetworkConfiguration.EnableRemoteAccess;
+ networkConfiguration.EnableUPnP = oldNetworkConfiguration.EnableUPnP;
+ networkConfiguration.IgnoreVirtualInterfaces = oldNetworkConfiguration.IgnoreVirtualInterfaces;
+ networkConfiguration.InternalHttpPort = oldNetworkConfiguration.HttpServerPortNumber;
+ networkConfiguration.InternalHttpsPort = oldNetworkConfiguration.HttpsPortNumber;
+ networkConfiguration.IsRemoteIPFilterBlacklist = oldNetworkConfiguration.IsRemoteIPFilterBlacklist;
+ networkConfiguration.KnownProxies = oldNetworkConfiguration.KnownProxies;
+ networkConfiguration.LocalNetworkAddresses = oldNetworkConfiguration.LocalNetworkAddresses;
+ networkConfiguration.LocalNetworkSubnets = oldNetworkConfiguration.LocalNetworkSubnets;
+ networkConfiguration.PublicHttpPort = oldNetworkConfiguration.PublicPort;
+ networkConfiguration.PublicHttpsPort = oldNetworkConfiguration.PublicHttpsPort;
+ networkConfiguration.PublishedServerUriBySubnet = oldNetworkConfiguration.PublishedServerUriBySubnet;
+ networkConfiguration.RemoteIPFilter = oldNetworkConfiguration.RemoteIPFilter;
+ networkConfiguration.RequireHttps = oldNetworkConfiguration.RequireHttps;
+
+ // Migrate old virtual interface name schema
+ var oldVirtualInterfaceNames = oldNetworkConfiguration.VirtualInterfaceNames;
+ if (oldVirtualInterfaceNames.Equals("vEthernet*", StringComparison.OrdinalIgnoreCase))
+ {
+ networkConfiguration.VirtualInterfaceNames = new string[] { "veth" };
+ }
+ else
+ {
+ networkConfiguration.VirtualInterfaceNames = oldVirtualInterfaceNames.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase).Split(',');
+ }
+
+ var networkConfigSerializer = new XmlSerializer(typeof(NetworkConfiguration));
+ var xmlWriterSettings = new XmlWriterSettings { Indent = true };
+ using var xmlWriter = XmlWriter.Create(path, xmlWriterSettings);
+ networkConfigSerializer.Serialize(xmlWriter, networkConfiguration);
+ }
+ }
+
+#pragma warning disable
+ public sealed class OldNetworkConfiguration
+ {
+ public const int DefaultHttpPort = 8096;
+
+ public const int DefaultHttpsPort = 8920;
+
+ private string _baseUrl = string.Empty;
+
+ public bool RequireHttps { get; set; }
+
+ public string CertificatePath { get; set; } = string.Empty;
+
+ public string CertificatePassword { get; set; } = string.Empty;
+
+ public string BaseUrl
+ {
+ get => _baseUrl;
+ set
+ {
+ // Normalize the start of the string
+ if (string.IsNullOrWhiteSpace(value))
+ {
+ // If baseUrl is empty, set an empty prefix string
+ _baseUrl = string.Empty;
+ return;
+ }
+
+ if (value[0] != '/')
+ {
+ // If baseUrl was not configured with a leading slash, append one for consistency
+ value = "/" + value;
+ }
+
+ // Normalize the end of the string
+ if (value[^1] == '/')
+ {
+ // If baseUrl was configured with a trailing slash, remove it for consistency
+ value = value.Remove(value.Length - 1);
+ }
+
+ _baseUrl = value;
+ }
+ }
+
+ public int PublicHttpsPort { get; set; } = DefaultHttpsPort;
+
+ public int HttpServerPortNumber { get; set; } = DefaultHttpPort;
+
+ public int HttpsPortNumber { get; set; } = DefaultHttpsPort;
+
+ public bool EnableHttps { get; set; }
+
+ public int PublicPort { get; set; } = DefaultHttpPort;
+
+ public bool UPnPCreateHttpPortMap { get; set; }
+
+ public string UDPPortRange { get; set; } = string.Empty;
+
+ public bool EnableIPV6 { get; set; }
+
+ public bool EnableIPV4 { get; set; } = true;
+
+ public bool EnableSSDPTracing { get; set; }
+
+ public string SSDPTracingFilter { get; set; } = string.Empty;
+
+ public int UDPSendCount { get; set; } = 2;
+
+ public int UDPSendDelay { get; set; } = 100;
+
+ public bool IgnoreVirtualInterfaces { get; set; } = true;
+
+ public string VirtualInterfaceNames { get; set; } = "vEthernet*";
+
+ public int GatewayMonitorPeriod { get; set; } = 60;
+
+ public bool EnableMultiSocketBinding { get; } = true;
+
+ public bool TrustAllIP6Interfaces { get; set; }
+
+ public string HDHomerunPortRange { get; set; } = string.Empty;
+
+ public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty();
+
+ public bool AutoDiscoveryTracing { get; set; }
+
+ public bool AutoDiscovery { get; set; } = true;
+
+ public string[] RemoteIPFilter { get; set; } = Array.Empty();
+
+ public bool IsRemoteIPFilterBlacklist { get; set; }
+
+ public bool EnableUPnP { get; set; }
+
+ public bool EnableRemoteAccess { get; set; } = true;
+
+ public string[] LocalNetworkSubnets { get; set; } = Array.Empty();
+
+ public string[] LocalNetworkAddresses { get; set; } = Array.Empty();
+ public string[] KnownProxies { get; set; } = Array.Empty();
+
+ public bool EnablePublishedServerUriByRequest { get; set; } = false;
+ }
+#pragma warning restore
+}
diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs
index 6394800f75..b759b6bca5 100644
--- a/Jellyfin.Server/Startup.cs
+++ b/Jellyfin.Server/Startup.cs
@@ -213,7 +213,7 @@ namespace Jellyfin.Server
mainApp.UseAuthorization();
mainApp.UseLanFiltering();
- mainApp.UseIpBasedAccessValidation();
+ mainApp.UseIPBasedAccessValidation();
mainApp.UseWebSocketHandler();
mainApp.UseServerStartupMessage();
diff --git a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs
index 6608704c0a..a1056b7c84 100644
--- a/MediaBrowser.Common/Extensions/HttpContextExtensions.cs
+++ b/MediaBrowser.Common/Extensions/HttpContextExtensions.cs
@@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Extensions
///
/// The HTTP context.
/// The remote caller IP address.
- public static IPAddress GetNormalizedRemoteIp(this HttpContext context)
+ public static IPAddress GetNormalizedRemoteIP(this HttpContext context)
{
// Default to the loopback address if no RemoteIpAddress is specified (i.e. during integration tests)
var ip = context.Connection.RemoteIpAddress ?? IPAddress.Loopback;
diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs
index b939397301..c51090e385 100644
--- a/MediaBrowser.Common/Net/INetworkManager.cs
+++ b/MediaBrowser.Common/Net/INetworkManager.cs
@@ -1,8 +1,9 @@
using System;
using System.Collections.Generic;
-using System.Collections.ObjectModel;
+using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.NetworkInformation;
+using MediaBrowser.Model.Net;
using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Common.Net
@@ -18,47 +19,32 @@ namespace MediaBrowser.Common.Net
event EventHandler NetworkChanged;
///
- /// Gets the published server urls list.
+ /// Gets a value indicating whether IPv4 is enabled.
///
- Dictionary PublishedServerUrls { get; }
+ bool IsIPv4Enabled { get; }
///
- /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
+ /// Gets a value indicating whether IPv6 is enabled.
///
- bool TrustAllIP6Interfaces { get; }
-
- ///
- /// Gets the remote address filter.
- ///
- Collection RemoteAddressFilter { get; }
-
- ///
- /// Gets or sets a value indicating whether iP6 is enabled.
- ///
- bool IsIP6Enabled { get; set; }
-
- ///
- /// Gets or sets a value indicating whether iP4 is enabled.
- ///
- bool IsIP4Enabled { get; set; }
+ bool IsIPv6Enabled { get; }
///
/// Calculates the list of interfaces to use for Kestrel.
///
- /// A Collection{IPObject} object containing all the interfaces to bind.
+ /// A IReadOnlyList{IPData} object containing all the interfaces to bind.
/// If all the interfaces are specified, and none are excluded, it returns zero items
/// to represent any address.
/// When false, return or for all interfaces.
- Collection GetAllBindInterfaces(bool individualInterfaces = false);
+ IReadOnlyList GetAllBindInterfaces(bool individualInterfaces = false);
///
- /// Returns a collection containing the loopback interfaces.
+ /// Returns a list containing the loopback interfaces.
///
- /// Collection{IPObject}.
- Collection GetLoopbacks();
+ /// IReadOnlyList{IPData}.
+ IReadOnlyList GetLoopbacks();
///
- /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo)
/// If no bind addresses are specified, an internal interface address is selected.
/// The priority of selection is as follows:-
///
@@ -72,90 +58,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.
+ /// Interfaces that have been specifically excluded from binding are not used in any of the calculations.
///
/// Source of the request.
/// Optional port returned, if it's part of an override.
- /// IP Address to use, or loopback address if all else fails.
- string GetBindInterface(IPObject source, out int? port);
+ /// IP address to use, or loopback address if all else fails.
+ string GetBindAddress(HttpRequest source, out int? port);
///
- /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
+ /// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo)
/// If no bind addresses are specified, an internal interface address is selected.
- /// (See .
- ///
- /// Source of the request.
- /// Optional port returned, if it's part of an override.
- /// IP Address to use, or loopback address if all else fails.
- string GetBindInterface(HttpRequest source, out int? port);
-
- ///
- /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
- /// If no bind addresses are specified, an internal interface address is selected.
- /// (See .
///
/// IP address of the request.
/// Optional port returned, if it's part of an override.
- /// IP Address to use, or loopback address if all else fails.
- string GetBindInterface(IPAddress source, out int? port);
+ /// Optional boolean denoting if published server overrides should be ignored. Defaults to false.
+ /// IP address to use, or loopback address if all else fails.
+ string GetBindAddress(IPAddress source, out int? port, bool skipOverrides = false);
///
- /// 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 .
///
/// Source of the request.
/// Optional port returned, if it's part of an override.
- /// IP Address to use, or loopback address if all else fails.
- string GetBindInterface(string source, out int? port);
-
- ///
- /// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses.
- ///
- /// IP address to check.
- /// True if it is.
- bool IsExcludedInterface(IPAddress address);
+ /// IP address to use, or loopback address if all else fails.
+ string GetBindAddress(string source, out int? port);
///
/// Get a list of all the MAC addresses associated with active interfaces.
///
/// List of MAC addresses.
- IReadOnlyCollection GetMacAddresses();
-
- ///
- /// Checks to see if the IP Address provided matches an interface that has a gateway.
- ///
- /// IP to check. Can be an IPAddress or an IPObject.
- /// Result of the check.
- bool IsGatewayInterface(IPObject? addressObj);
-
- ///
- /// Checks to see if the IP Address provided matches an interface that has a gateway.
- ///
- /// IP to check. Can be an IPAddress or an IPObject.
- /// Result of the check.
- bool IsGatewayInterface(IPAddress? addressObj);
-
- ///
- /// Returns true if the address is a private address.
- /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
- ///
- /// Address to check.
- /// True or False.
- bool IsPrivateAddressRange(IPObject address);
+ IReadOnlyList GetMacAddresses();
///
/// Returns true if the address is part of the user defined LAN.
- /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
///
/// IP to check.
/// True if endpoint is within the LAN range.
@@ -163,76 +109,31 @@ namespace MediaBrowser.Common.Net
///
/// Returns true if the address is part of the user defined LAN.
- /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
- ///
- /// IP to check.
- /// True if endpoint is within the LAN range.
- bool IsInLocalNetwork(IPObject address);
-
- ///
- /// Returns true if the address is part of the user defined LAN.
- /// The configuration option TrustIP6Interfaces overrides this functions behaviour.
///
/// IP to check.
/// True if endpoint is within the LAN range.
bool IsInLocalNetwork(IPAddress address);
///
- /// Attempts to convert the token to an IP address, permitting for interface descriptions and indexes.
- /// eg. "eth1", or "TP-LINK Wireless USB Adapter".
+ /// Attempts to convert the interface name to an IP address.
+ /// eg. "eth1", or "enp3s5".
///
- /// Token to parse.
- /// Resultant object's ip addresses, if successful.
+ /// Interface name.
+ /// Resulting object's IP addresses, if successful.
/// Success of the operation.
- bool TryParseInterface(string token, out Collection? result);
+ bool TryParseInterface(string intf, [NotNullWhen(true)] out IReadOnlyList? result);
///
- /// Parses an array of strings into a Collection{IPObject}.
+ /// Returns all internal (LAN) bind interface addresses.
///
- /// Values to parse.
- /// When true, only include values beginning with !. When false, ignore ! values.
- /// IPCollection object containing the value strings.
- Collection CreateIPCollection(string[] values, bool negated = false);
+ /// An list of internal (LAN) interfaces addresses.
+ IReadOnlyList GetInternalBindAddresses();
///
- /// Returns all the internal Bind interface addresses.
+ /// Checks if has access to the server.
///
- /// An internal list of interfaces addresses.
- Collection GetInternalBindAddresses();
-
- ///
- /// Checks to see if an IP address is still a valid interface address.
- ///
- /// IP address to check.
- /// True if it is.
- bool IsValidInterfaceAddress(IPAddress address);
-
- ///
- /// Returns true if the IP address is in the excluded list.
- ///
- /// IP to check.
- /// True if excluded.
- bool IsExcluded(IPAddress ip);
-
- ///
- /// Returns true if the IP address is in the excluded list.
- ///
- /// IP to check.
- /// True if excluded.
- bool IsExcluded(EndPoint ip);
-
- ///
- /// Gets the filtered LAN ip addresses.
- ///
- /// Optional filter for the list.
- /// Returns a filtered list of LAN addresses.
- Collection GetFilteredLANSubnets(Collection? filter = null);
-
- ///
- /// Checks to see if has access.
- ///
- /// IP Address of client.
- /// True if has access, otherwise false.
- bool HasRemoteAccess(IPAddress remoteIp);
+ /// IP address of the client.
+ /// True if it has access, otherwise false.
+ bool HasRemoteAccess(IPAddress remoteIP);
}
}
diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs
deleted file mode 100644
index ec76a43b6f..0000000000
--- a/MediaBrowser.Common/Net/IPHost.cs
+++ /dev/null
@@ -1,441 +0,0 @@
-using System;
-using System.Diagnostics;
-using System.Linq;
-using System.Net;
-using System.Net.Sockets;
-using System.Text.RegularExpressions;
-
-namespace MediaBrowser.Common.Net
-{
- ///
- /// Object that holds a host name.
- ///
- public class IPHost : IPObject
- {
- ///
- /// Gets or sets timeout value before resolve required, in minutes.
- ///
- public const int Timeout = 30;
-
- ///
- /// Represents an IPHost that has no value.
- ///
- public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None);
-
- ///
- /// Time when last resolved in ticks.
- ///
- private DateTime? _lastResolved = null;
-
- ///
- /// Gets the IP Addresses, attempting to resolve the name, if there are none.
- ///
- private IPAddress[] _addresses;
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Host name to assign.
- public IPHost(string name)
- {
- HostName = name ?? throw new ArgumentNullException(nameof(name));
- _addresses = Array.Empty();
- Resolved = false;
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Host name to assign.
- /// Address to assign.
- private IPHost(string name, IPAddress address)
- {
- HostName = name ?? throw new ArgumentNullException(nameof(name));
- _addresses = new IPAddress[] { address ?? throw new ArgumentNullException(nameof(address)) };
- Resolved = !address.Equals(IPAddress.None);
- }
-
- ///
- /// Gets or sets the object's first IP address.
- ///
- public override IPAddress Address
- {
- get
- {
- return ResolveHost() ? this[0] : IPAddress.None;
- }
-
- set
- {
- // Not implemented, as a host's address is determined by DNS.
- throw new NotImplementedException("The address of a host is determined by DNS.");
- }
- }
-
- ///
- /// Gets or sets the object's first IP's subnet prefix.
- /// The setter does nothing, but shouldn't raise an exception.
- ///
- public override byte PrefixLength
- {
- get => (byte)(ResolveHost() ? 128 : 32);
-
- // Not implemented, as a host object can only have a prefix length of 128 (IPv6) or 32 (IPv4) prefix length,
- // which is automatically determined by it's IP type. Anything else is meaningless.
- set => throw new NotImplementedException();
- }
-
- ///
- /// Gets a value indicating whether the address has a value.
- ///
- public bool HasAddress => _addresses.Length != 0;
-
- ///
- /// Gets the host name of this object.
- ///
- public string HostName { get; }
-
- ///
- /// Gets a value indicating whether this host has attempted to be resolved.
- ///
- public bool Resolved { get; private set; }
-
- ///
- /// Gets or sets the IP Addresses associated with this object.
- ///
- /// Index of address.
- public IPAddress this[int index]
- {
- get
- {
- ResolveHost();
- return index >= 0 && index < _addresses.Length ? _addresses[index] : IPAddress.None;
- }
- }
-
- ///
- /// Attempts to parse the host string.
- ///
- /// Host name to parse.
- /// Object representing the string, if it has successfully been parsed.
- /// true if the parsing is successful, false if not.
- public static bool TryParse(string host, out IPHost hostObj)
- {
- if (string.IsNullOrWhiteSpace(host))
- {
- hostObj = IPHost.None;
- return false;
- }
-
- // See if it's an IPv6 with port address e.g. [::1] or [::1]:120.
- int i = host.IndexOf(']', StringComparison.Ordinal);
- if (i != -1)
- {
- return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj);
- }
-
- if (IPNetAddress.TryParse(host, out var netAddress))
- {
- // Host name is an ip address, so fake resolve.
- hostObj = new IPHost(host, netAddress.Address);
- return true;
- }
-
- // Is it a host, IPv4/6 with/out port?
- string[] hosts = host.Split(':');
-
- if (hosts.Length <= 2)
- {
- // This is either a hostname: port, or an IP4:port.
- host = hosts[0];
-
- if (string.Equals("localhost", host, StringComparison.OrdinalIgnoreCase))
- {
- hostObj = new IPHost(host);
- return true;
- }
-
- if (IPAddress.TryParse(host, out var netIP))
- {
- // Host name is an ip address, so fake resolve.
- hostObj = new IPHost(host, netIP);
- return true;
- }
- }
- else
- {
- // Invalid host name, as it cannot contain :
- hostObj = new IPHost(string.Empty, IPAddress.None);
- return false;
- }
-
- // Use regular expression as CheckHostName isn't RFC5892 compliant.
- // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation
- string pattern = @"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)$";
-
- if (Regex.IsMatch(host, pattern))
- {
- hostObj = new IPHost(host);
- return true;
- }
-
- hostObj = IPHost.None;
- return false;
- }
-
- ///
- /// Attempts to parse the host string.
- ///
- /// Host name to parse.
- /// Object representing the string, if it has successfully been parsed.
- public static IPHost Parse(string host)
- {
- if (IPHost.TryParse(host, out IPHost res))
- {
- return res;
- }
-
- throw new InvalidCastException($"Host does not contain a valid value. {host}");
- }
-
- ///
- /// Attempts to parse the host string, ensuring that it resolves only to a specific IP type.
- ///
- /// Host name to parse.
- /// Addressfamily filter.
- /// Object representing the string, if it has successfully been parsed.
- public static IPHost Parse(string host, AddressFamily family)
- {
- if (IPHost.TryParse(host, out IPHost res))
- {
- if (family == AddressFamily.InterNetwork)
- {
- res.Remove(AddressFamily.InterNetworkV6);
- }
- else
- {
- res.Remove(AddressFamily.InterNetwork);
- }
-
- return res;
- }
-
- throw new InvalidCastException($"Host does not contain a valid value. {host}");
- }
-
- ///
- /// Returns the Addresses that this item resolved to.
- ///
- /// IPAddress Array.
- public IPAddress[] GetAddresses()
- {
- ResolveHost();
- return _addresses;
- }
-
- ///
- public override bool Contains(IPAddress address)
- {
- if (address 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;
- }
-
- ///
- public override bool Equals(IPObject? other)
- {
- if (other is IPHost otherObj)
- {
- // Do we have the name Hostname?
- if (string.Equals(otherObj.HostName, HostName, StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
-
- if (!ResolveHost() || !otherObj.ResolveHost())
- {
- return false;
- }
-
- // Do any of our IP addresses match?
- foreach (IPAddress addr in _addresses)
- {
- foreach (IPAddress otherAddress in otherObj._addresses)
- {
- if (addr.Equals(otherAddress))
- {
- return true;
- }
- }
- }
- }
-
- return false;
- }
-
- ///
- public override bool IsIP6()
- {
- // Returns true if interfaces are only IP6.
- if (ResolveHost())
- {
- foreach (IPAddress i in _addresses)
- {
- if (i.AddressFamily != AddressFamily.InterNetworkV6)
- {
- return false;
- }
- }
-
- return true;
- }
-
- return false;
- }
-
- ///
- public override string ToString()
- {
- // StringBuilder not optimum here.
- string output = string.Empty;
- if (_addresses.Length > 0)
- {
- bool moreThanOne = _addresses.Length > 1;
- if (moreThanOne)
- {
- output = "[";
- }
-
- foreach (var i in _addresses)
- {
- if (Address.Equals(IPAddress.None) && Address.AddressFamily == AddressFamily.Unspecified)
- {
- output += HostName + ",";
- }
- else if (i.Equals(IPAddress.Any))
- {
- output += "Any IP4 Address,";
- }
- else if (Address.Equals(IPAddress.IPv6Any))
- {
- output += "Any IP6 Address,";
- }
- else if (i.Equals(IPAddress.Broadcast))
- {
- output += "Any Address,";
- }
- else if (i.AddressFamily == AddressFamily.InterNetwork)
- {
- output += $"{i}/32,";
- }
- else
- {
- output += $"{i}/128,";
- }
- }
-
- output = output[..^1];
-
- if (moreThanOne)
- {
- output += "]";
- }
- }
- else
- {
- output = HostName;
- }
-
- return output;
- }
-
- ///
- public override void Remove(AddressFamily family)
- {
- if (ResolveHost())
- {
- _addresses = _addresses.Where(p => p.AddressFamily != family).ToArray();
- }
- }
-
- ///
- public override bool Contains(IPObject address)
- {
- // An IPHost cannot contain another IPObject, it can only be equal.
- return Equals(address);
- }
-
- ///
- protected override IPObject CalculateNetworkAddress()
- {
- var (address, prefixLength) = NetworkAddressOf(this[0], PrefixLength);
- return new IPNetAddress(address, prefixLength);
- }
-
- ///
- /// Attempt to resolve the ip address of a host.
- ///
- /// true if any addresses have been resolved, otherwise false.
- private bool ResolveHost()
- {
- // When was the last time we resolved?
- _lastResolved ??= DateTime.UtcNow;
-
- // If we haven't resolved before, or our timer has run out...
- if ((_addresses.Length == 0 && !Resolved) || (DateTime.UtcNow > _lastResolved.Value.AddMinutes(Timeout)))
- {
- _lastResolved = DateTime.UtcNow;
- ResolveHostInternal();
- Resolved = true;
- }
-
- return _addresses.Length > 0;
- }
-
- ///
- /// Task that looks up a Host name and returns its IP addresses.
- ///
- private void ResolveHostInternal()
- {
- var hostName = HostName;
- if (string.IsNullOrEmpty(hostName))
- {
- return;
- }
-
- // Resolves the host name - so save a DNS lookup.
- if (string.Equals(hostName, "localhost", StringComparison.OrdinalIgnoreCase))
- {
- _addresses = new IPAddress[] { IPAddress.Loopback, IPAddress.IPv6Loopback };
- return;
- }
-
- if (Uri.CheckHostName(hostName) == UriHostNameType.Dns)
- {
- try
- {
- _addresses = Dns.GetHostEntry(hostName).AddressList;
- }
- catch (SocketException ex)
- {
- // Log and then ignore socket errors, as the result value will just be an empty array.
- Debug.WriteLine("GetHostAddresses failed with {Message}.", ex.Message);
- }
- }
- }
- }
-}
diff --git a/MediaBrowser.Common/Net/IPNetAddress.cs b/MediaBrowser.Common/Net/IPNetAddress.cs
deleted file mode 100644
index de72d978ec..0000000000
--- a/MediaBrowser.Common/Net/IPNetAddress.cs
+++ /dev/null
@@ -1,278 +0,0 @@
-using System;
-using System.Net;
-using System.Net.Sockets;
-
-namespace MediaBrowser.Common.Net
-{
- ///
- /// An object that holds and IP address and subnet mask.
- ///
- public class IPNetAddress : IPObject
- {
- ///
- /// Represents an IPNetAddress that has no value.
- ///
- public static readonly IPNetAddress None = new IPNetAddress(IPAddress.None);
-
- ///
- /// IPv4 multicast address.
- ///
- public static readonly IPAddress SSDPMulticastIPv4 = IPAddress.Parse("239.255.255.250");
-
- ///
- /// IPv6 local link multicast address.
- ///
- public static readonly IPAddress SSDPMulticastIPv6LinkLocal = IPAddress.Parse("ff02::C");
-
- ///
- /// IPv6 site local multicast address.
- ///
- public static readonly IPAddress SSDPMulticastIPv6SiteLocal = IPAddress.Parse("ff05::C");
-
- ///
- /// IP4Loopback address host.
- ///
- public static readonly IPNetAddress IP4Loopback = IPNetAddress.Parse("127.0.0.1/8");
-
- ///
- /// IP6Loopback address host.
- ///
- public static readonly IPNetAddress IP6Loopback = new IPNetAddress(IPAddress.IPv6Loopback);
-
- ///
- /// Object's IP address.
- ///
- private IPAddress _address;
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// Address to assign.
- public IPNetAddress(IPAddress address)
- {
- _address = address ?? throw new ArgumentNullException(nameof(address));
- PrefixLength = (byte)(address.AddressFamily == AddressFamily.InterNetwork ? 32 : 128);
- }
-
- ///
- /// Initializes a new instance of the class.
- ///
- /// IP Address.
- /// Mask as a CIDR.
- public IPNetAddress(IPAddress address, byte prefixLength)
- {
- if (address?.IsIPv4MappedToIPv6 ?? throw new ArgumentNullException(nameof(address)))
- {
- _address = address.MapToIPv4();
- }
- else
- {
- _address = address;
- }
-
- PrefixLength = prefixLength;
- }
-
- ///
- /// Gets or sets the object's IP address.
- ///
- public override IPAddress Address
- {
- get
- {
- return _address;
- }
-
- set
- {
- _address = value ?? IPAddress.None;
- }
- }
-
- ///
- public override byte PrefixLength { get; set; }
-
- ///
- /// Try to parse the address and subnet strings into an IPNetAddress object.
- ///
- /// IP address to parse. Can be CIDR or X.X.X.X notation.
- /// Resultant object.
- /// True if the values parsed successfully. False if not, resulting in the IP being null.
- public static bool TryParse(string addr, out IPNetAddress ip)
- {
- if (!string.IsNullOrEmpty(addr))
- {
- addr = addr.Trim();
-
- // Try to parse it as is.
- if (IPAddress.TryParse(addr, out IPAddress? res))
- {
- ip = new IPNetAddress(res);
- return true;
- }
-
- // Is it a network?
- string[] tokens = addr.Split('/');
-
- if (tokens.Length == 2)
- {
- tokens[0] = tokens[0].TrimEnd();
- tokens[1] = tokens[1].TrimStart();
-
- if (IPAddress.TryParse(tokens[0], out res))
- {
- // Is the subnet part a cidr?
- if (byte.TryParse(tokens[1], out byte cidr))
- {
- ip = new IPNetAddress(res, cidr);
- return true;
- }
-
- // Is the subnet in x.y.a.b form?
- if (IPAddress.TryParse(tokens[1], out IPAddress? mask))
- {
- ip = new IPNetAddress(res, MaskToCidr(mask));
- return true;
- }
- }
- }
- }
-
- ip = None;
- return false;
- }
-
- ///
- /// Parses the string provided, throwing an exception if it is badly formed.
- ///
- /// String to parse.
- /// IPNetAddress object.
- public static IPNetAddress Parse(string addr)
- {
- if (TryParse(addr, out IPNetAddress o))
- {
- return o;
- }
-
- throw new ArgumentException("Unable to recognise object :" + addr);
- }
-
- ///
- public override bool Contains(IPAddress address)
- {
- ArgumentNullException.ThrowIfNull(address);
-
- if (address.IsIPv4MappedToIPv6)
- {
- address = address.MapToIPv4();
- }
-
- if (address.AddressFamily != AddressFamily)
- {
- return false;
- }
-
- var (altAddress, altPrefix) = NetworkAddressOf(address, PrefixLength);
- return NetworkAddress.Address.Equals(altAddress) && NetworkAddress.PrefixLength >= altPrefix;
- }
-
- ///
- public override bool Contains(IPObject address)
- {
- if (address is IPHost addressObj && addressObj.HasAddress)
- {
- foreach (IPAddress addr in addressObj.GetAddresses())
- {
- if (Contains(addr))
- {
- return true;
- }
- }
- }
- else if (address is IPNetAddress netaddrObj)
- {
- // Have the same network address, but different subnets?
- if (NetworkAddress.Address.Equals(netaddrObj.NetworkAddress.Address))
- {
- return NetworkAddress.PrefixLength <= netaddrObj.PrefixLength;
- }
-
- var altAddress = NetworkAddressOf(netaddrObj.Address, PrefixLength).Address;
- return NetworkAddress.Address.Equals(altAddress);
- }
-
- return false;
- }
-
- ///
- public override bool Equals(IPObject? other)
- {
- if (other is IPNetAddress otherObj && !Address.Equals(IPAddress.None) && !otherObj.Address.Equals(IPAddress.None))
- {
- return Address.Equals(otherObj.Address) &&
- PrefixLength == otherObj.PrefixLength;
- }
-
- return false;
- }
-
- ///
- public override bool Equals(IPAddress ip)
- {
- if (ip is not null && !ip.Equals(IPAddress.None) && !Address.Equals(IPAddress.None))
- {
- return ip.Equals(Address);
- }
-
- return false;
- }
-
- ///
- public override string ToString()
- {
- return ToString(false);
- }
-
- ///
- /// Returns a textual representation of this object.
- ///
- /// Set to true, if the subnet is to be excluded as part of the address.
- /// String representation of this object.
- public string ToString(bool shortVersion)
- {
- if (!Address.Equals(IPAddress.None))
- {
- if (Address.Equals(IPAddress.Any))
- {
- return "Any IP4 Address";
- }
-
- if (Address.Equals(IPAddress.IPv6Any))
- {
- return "Any IP6 Address";
- }
-
- if (Address.Equals(IPAddress.Broadcast))
- {
- return "Any Address";
- }
-
- if (shortVersion)
- {
- return Address.ToString();
- }
-
- return $"{Address}/{PrefixLength}";
- }
-
- return string.Empty;
- }
-
- ///
- protected override IPObject CalculateNetworkAddress()
- {
- var (address, prefixLength) = NetworkAddressOf(_address, PrefixLength);
- return new IPNetAddress(address, prefixLength);
- }
- }
-}
diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs
deleted file mode 100644
index 93655234b0..0000000000
--- 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
-{
- ///
- /// Base network object class.
- ///
- public abstract class IPObject : IEquatable
- {
- ///
- /// The network address of this object.
- ///
- private IPObject? _networkAddress;
-
- ///
- /// Gets or sets a user defined value that is associated with this object.
- ///
- public int Tag { get; set; }
-
- ///
- /// Gets or sets the object's IP address.
- ///
- public abstract IPAddress Address { get; set; }
-
- ///
- /// Gets the object's network address.
- ///
- public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress();
-
- ///
- /// Gets or sets the object's IP address.
- ///
- public abstract byte PrefixLength { get; set; }
-
- ///
- /// Gets the AddressFamily of this object.
- ///
- public AddressFamily AddressFamily
- {
- get
- {
- // Keep terms separate as Address performs other functions in inherited objects.
- IPAddress address = Address;
- return address.Equals(IPAddress.None) ? AddressFamily.Unspecified : address.AddressFamily;
- }
- }
-
- ///
- /// Returns the network address of an object.
- ///
- /// IP Address to convert.
- /// Subnet prefix.
- /// IPAddress.
- public static (IPAddress Address, byte PrefixLength) NetworkAddressOf(IPAddress address, byte prefixLength)
- {
- 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 addressBytes = stackalloc byte[address.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
- address.TryWriteBytes(addressBytes, out _);
-
- int div = prefixLength / 8;
- int mod = prefixLength % 8;
- if (mod != 0)
- {
- // Prefix length is counted right to left, so subtract 8 so we know how many bits to clear.
- mod = 8 - mod;
-
- // Shift out the bits from the octet that we don't want, by moving right then back left.
- addressBytes[div] = (byte)((int)addressBytes[div] >> mod << mod);
- // Move on the next byte.
- div++;
- }
-
- // Blank out the remaining octets from mod + 1 to the end of the byte array. (192.168.2.240/16 becomes 192.168.0.0)
- for (int octet = div; octet < addressBytes.Length; octet++)
- {
- addressBytes[octet] = 0;
- }
-
- // Return the network address for the prefix.
- return (new IPAddress(addressBytes), prefixLength);
- }
-
- ///
- /// Tests to see if the ip address is an IP6 address.
- ///
- /// Value to test.
- /// True if it is.
- public static bool IsIP6(IPAddress address)
- {
- ArgumentNullException.ThrowIfNull(address);
-
- if (address.IsIPv4MappedToIPv6)
- {
- address = address.MapToIPv4();
- }
-
- return !address.Equals(IPAddress.None) && (address.AddressFamily == AddressFamily.InterNetworkV6);
- }
-
- ///
- /// Tests to see if the address in the private address range.
- ///
- /// Object to test.
- /// True if it contains a private address.
- public static bool IsPrivateAddressRange(IPAddress address)
- {
- ArgumentNullException.ThrowIfNull(address);
-
- if (!address.Equals(IPAddress.None))
- {
- if (address.IsIPv4MappedToIPv6)
- {
- address = address.MapToIPv4();
- }
-
- if (address.AddressFamily == AddressFamily.InterNetwork)
- {
- // GetAddressBytes
- Span octet = stackalloc byte[4];
- address.TryWriteBytes(octet, out _);
-
- return (octet[0] == 10)
- || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918
- || (octet[0] == 192 && octet[1] == 168) // RFC1918
- || (octet[0] == 127); // RFC1122
- }
- else
- {
- // GetAddressBytes
- Span octet = stackalloc byte[16];
- address.TryWriteBytes(octet, out _);
-
- uint word = (uint)(octet[0] << 8) + octet[1];
-
- return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link.
- || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address.
- }
- }
-
- return false;
- }
-
- ///
- /// Returns true if the IPAddress contains an IP6 Local link address.
- ///
- /// IPAddress object to check.
- /// True if it is a local link address.
- ///
- /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress
- /// it appears that the IPAddress.IsIPv6LinkLocal is out of date.
- ///
- public static bool IsIPv6LinkLocal(IPAddress address)
- {
- ArgumentNullException.ThrowIfNull(address);
-
- if (address.IsIPv4MappedToIPv6)
- {
- address = address.MapToIPv4();
- }
-
- if (address.AddressFamily != AddressFamily.InterNetworkV6)
- {
- return false;
- }
-
- // GetAddressBytes
- Span octet = stackalloc byte[16];
- address.TryWriteBytes(octet, out _);
- uint word = (uint)(octet[0] << 8) + octet[1];
-
- return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link.
- }
-
- ///
- /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
- ///
- /// Subnet mask in CIDR notation.
- /// IPv4 or IPv6 family.
- /// String value of the subnet mask in dotted decimal notation.
- public static IPAddress CidrToMask(byte cidr, AddressFamily family)
- {
- uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr);
- addr = ((addr & 0xff000000) >> 24)
- | ((addr & 0x00ff0000) >> 8)
- | ((addr & 0x0000ff00) << 8)
- | ((addr & 0x000000ff) << 24);
- return new IPAddress(addr);
- }
-
- ///
- /// Convert a mask to a CIDR. IPv4 only.
- /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask.
- ///
- /// Subnet mask.
- /// Byte CIDR representing the mask.
- public static byte MaskToCidr(IPAddress mask)
- {
- ArgumentNullException.ThrowIfNull(mask);
-
- byte cidrnet = 0;
- if (!mask.Equals(IPAddress.Any))
- {
- // GetAddressBytes
- Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
- mask.TryWriteBytes(bytes, out _);
-
- var zeroed = false;
- for (var i = 0; i < bytes.Length; i++)
- {
- for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1)
- {
- if (zeroed)
- {
- // Invalid netmask.
- return (byte)~cidrnet;
- }
-
- if ((v & 0x80) == 0)
- {
- zeroed = true;
- }
- else
- {
- cidrnet++;
- }
- }
- }
- }
-
- return cidrnet;
- }
-
- ///
- /// Tests to see if this object is a Loopback address.
- ///
- /// True if it is.
- public virtual bool IsLoopback()
- {
- return IPAddress.IsLoopback(Address);
- }
-
- ///
- /// Removes all addresses of a specific type from this object.
- ///
- /// Type of address to remove.
- public virtual void Remove(AddressFamily family)
- {
- // This method only performs a function in the IPHost implementation of IPObject.
- }
-
- ///
- /// Tests to see if this object is an IPv6 address.
- ///
- /// True if it is.
- public virtual bool IsIP6()
- {
- return IsIP6(Address);
- }
-
- ///
- /// Returns true if this IP address is in the RFC private address range.
- ///
- /// True this object has a private address.
- public virtual bool IsPrivateAddressRange()
- {
- return IsPrivateAddressRange(Address);
- }
-
- ///
- /// Compares this to the object passed as a parameter.
- ///
- /// Object to compare to.
- /// Equality result.
- public virtual bool Equals(IPAddress ip)
- {
- if (ip is not null)
- {
- if (ip.IsIPv4MappedToIPv6)
- {
- ip = ip.MapToIPv4();
- }
-
- return !Address.Equals(IPAddress.None) && Address.Equals(ip);
- }
-
- return false;
- }
-
- ///
- /// Compares this to the object passed as a parameter.
- ///
- /// Object to compare to.
- /// Equality result.
- public virtual bool Equals(IPObject? other)
- {
- if (other is not null)
- {
- return !Address.Equals(IPAddress.None) && Address.Equals(other.Address);
- }
-
- return false;
- }
-
- ///
- /// Compares the address in this object and the address in the object passed as a parameter.
- ///
- /// Object's IP address to compare to.
- /// Comparison result.
- public abstract bool Contains(IPObject address);
-
- ///
- /// Compares the address in this object and the address in the object passed as a parameter.
- ///
- /// Object's IP address to compare to.
- /// Comparison result.
- public abstract bool Contains(IPAddress address);
-
- ///
- public override int GetHashCode()
- {
- return Address.GetHashCode();
- }
-
- ///
- public override bool Equals(object? obj)
- {
- return Equals(obj as IPObject);
- }
-
- ///
- /// Calculates the network address of this object.
- ///
- /// Returns the network address of this object.
- protected abstract IPObject CalculateNetworkAddress();
- }
-}
diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs
index 5e5e5b81b7..47475b3da9 100644
--- a/MediaBrowser.Common/Net/NetworkExtensions.cs
+++ b/MediaBrowser.Common/Net/NetworkExtensions.cs
@@ -1,6 +1,12 @@
using System;
-using System.Collections.ObjectModel;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
using System.Net;
+using System.Net.Sockets;
+using System.Text.RegularExpressions;
+using Jellyfin.Extensions;
+using Microsoft.AspNetCore.HttpOverrides;
namespace MediaBrowser.Common.Net
{
@@ -9,240 +15,336 @@ namespace MediaBrowser.Common.Net
///
public static class NetworkExtensions
{
+ // Use regular expression as CheckHostName isn't RFC5892 compliant.
+ // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation
+ private static readonly Regex _fqdnRegex = new Regex(@"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$");
+
///
- /// Add an address to the collection.
+ /// Returns true if the IPAddress contains an IP6 Local link address.
///
- /// The .
- /// Item to add.
- public static void AddItem(this Collection source, IPAddress ip)
+ /// IPAddress object to check.
+ /// True if it is a local link address.
+ ///
+ /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress
+ /// it appears that the IPAddress.IsIPv6LinkLocal is out of date.
+ ///
+ public static bool IsIPv6LinkLocal(IPAddress address)
{
- if (!source.ContainsAddress(ip))
+ ArgumentNullException.ThrowIfNull(address);
+
+ if (address.IsIPv4MappedToIPv6)
{
- source.Add(new IPNetAddress(ip, 32));
+ address = address.MapToIPv4();
}
- }
- ///
- /// Adds a network to the collection.
- ///
- /// The .
- /// Item to add.
- /// If true the values are treated as subnets.
- /// If false items are addresses.
- public static void AddItem(this Collection source, IPObject item, bool itemsAreNetworks = true)
- {
- if (!source.ContainsAddress(item) || !itemsAreNetworks)
- {
- source.Add(item);
- }
- }
-
- ///
- /// Converts this object to a string.
- ///
- /// The .
- /// Returns a string representation of this object.
- public static string AsString(this Collection source)
- {
- return $"[{string.Join(',', source)}]";
- }
-
- ///
- /// Returns true if the collection contains an item with the ip address,
- /// or the ip address falls within any of the collection's network ranges.
- ///
- /// The .
- /// The item to look for.
- /// True if the collection contains the item.
- public static bool ContainsAddress(this Collection source, IPAddress item)
- {
- if (source.Count == 0)
+ if (address.AddressFamily != AddressFamily.InterNetworkV6)
{
return false;
}
- ArgumentNullException.ThrowIfNull(item);
+ // GetAddressBytes
+ Span octet = stackalloc byte[16];
+ address.TryWriteBytes(octet, out _);
+ uint word = (uint)(octet[0] << 8) + octet[1];
- if (item.IsIPv4MappedToIPv6)
- {
- item = item.MapToIPv4();
- }
-
- foreach (var i in source)
- {
- if (i.Contains(item))
- {
- return true;
- }
- }
-
- return false;
+ return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link.
}
///
- /// Returns true if the collection contains an item with the ip address,
- /// or the ip address falls within any of the collection's network ranges.
+ /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
///
- /// The .
- /// The item to look for.
- /// True if the collection contains the item.
- public static bool ContainsAddress(this Collection source, IPObject item)
+ /// Subnet mask in CIDR notation.
+ /// IPv4 or IPv6 family.
+ /// String value of the subnet mask in dotted decimal notation.
+ public static IPAddress CidrToMask(byte cidr, AddressFamily family)
{
- if (source.Count == 0)
- {
- return false;
- }
-
- ArgumentNullException.ThrowIfNull(item);
-
- foreach (var i in source)
- {
- if (i.Contains(item))
- {
- return true;
- }
- }
-
- return false;
+ uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? 32 : 128) - cidr);
+ addr = ((addr & 0xff000000) >> 24)
+ | ((addr & 0x00ff0000) >> 8)
+ | ((addr & 0x0000ff00) << 8)
+ | ((addr & 0x000000ff) << 24);
+ return new IPAddress(addr);
}
///
- /// Compares two Collection{IPObject} objects. The order is ignored.
+ /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
///
- /// The .
- /// Item to compare to.
- /// True if both are equal.
- public static bool Compare(this Collection source, Collection dest)
+ /// Subnet mask in CIDR notation.
+ /// IPv4 or IPv6 family.
+ /// String value of the subnet mask in dotted decimal notation.
+ public static IPAddress CidrToMask(int cidr, AddressFamily family)
{
- if (dest is null || source.Count != dest.Count)
+ uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? 32 : 128) - cidr);
+ addr = ((addr & 0xff000000) >> 24)
+ | ((addr & 0x00ff0000) >> 8)
+ | ((addr & 0x0000ff00) << 8)
+ | ((addr & 0x000000ff) << 24);
+ return new IPAddress(addr);
+ }
+
+ ///
+ /// Convert a subnet mask to a CIDR. IPv4 only.
+ /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask.
+ ///
+ /// Subnet mask.
+ /// Byte CIDR representing the mask.
+ public static byte MaskToCidr(IPAddress mask)
+ {
+ ArgumentNullException.ThrowIfNull(mask);
+
+ byte cidrnet = 0;
+ if (mask.Equals(IPAddress.Any))
{
- return false;
+ return cidrnet;
}
- foreach (var sourceItem in source)
+ // GetAddressBytes
+ Span bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
+ if (!mask.TryWriteBytes(bytes, out var bytesWritten))
{
- bool found = false;
- foreach (var destItem in dest)
+ Console.WriteLine("Unable to write address bytes, only {Bytes} bytes written.", bytesWritten);
+ }
+
+ var zeroed = false;
+ for (var i = 0; i < bytes.Length; i++)
+ {
+ for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1)
{
- if (sourceItem.Equals(destItem))
+ if (zeroed)
{
- found = true;
- break;
+ // Invalid netmask.
+ return (byte)~cidrnet;
+ }
+
+ if ((v & 0x80) == 0)
+ {
+ zeroed = true;
+ }
+ else
+ {
+ cidrnet++;
}
}
-
- if (!found)
- {
- return false;
- }
}
- return true;
+ return cidrnet;
}
///
- /// Returns a collection containing the subnets of this collection given.
+ /// Converts an IPAddress into a string.
+ /// IPv6 addresses are returned in [ ], with their scope removed.
///
- /// The .
- /// Collection{IPObject} object containing the subnets.
- public static Collection AsNetworks(this Collection source)
+ /// Address to convert.
+ /// URI safe conversion of the address.
+ public static string FormatIPString(IPAddress? address)
{
- ArgumentNullException.ThrowIfNull(source);
-
- Collection res = new Collection();
-
- foreach (IPObject i in source)
+ if (address is null)
{
- if (i is IPNetAddress nw)
+ return string.Empty;
+ }
+
+ var str = address.ToString();
+ if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ int i = str.IndexOf('%', StringComparison.Ordinal);
+ if (i != -1)
{
- // Add the subnet calculated from the interface address/mask.
- var na = nw.NetworkAddress;
- na.Tag = i.Tag;
- res.AddItem(na);
+ str = str.Substring(0, i);
}
- else if (i is IPHost ipHost)
+
+ return $"[{str}]";
+ }
+
+ return str;
+ }
+
+ ///
+ /// Try parsing an array of strings into objects, respecting exclusions.
+ /// Elements without a subnet mask will be represented as with a single IP.
+ ///
+ /// Input string array to be parsed.
+ /// Collection of .
+ /// Boolean signaling if negated or not negated values should be parsed.
+ /// True if parsing was successful.
+ public static bool TryParseToSubnets(string[] values, [NotNullWhen(true)] out IReadOnlyList? result, bool negated = false)
+ {
+ if (values is null || values.Length == 0)
+ {
+ result = null;
+ return false;
+ }
+
+ var tmpResult = new List();
+ for (int a = 0; a < values.Length; a++)
+ {
+ if (TryParseToSubnet(values[a], out var innerResult, negated))
{
- // Flatten out IPHost and add all its ip addresses.
- foreach (var addr in ipHost.GetAddresses())
+ tmpResult.Add(innerResult);
+ }
+ }
+
+ result = tmpResult;
+ return tmpResult.Count > 0;
+ }
+
+ ///
+ /// Try parsing a string into an , respecting exclusions.
+ /// Inputs without a subnet mask will be represented as with a single IP.
+ ///
+ /// Input string to be parsed.
+ /// An .
+ /// Boolean signaling if negated or not negated values should be parsed.
+ /// True if parsing was successful.
+ public static bool TryParseToSubnet(ReadOnlySpan value, [NotNullWhen(true)] out IPNetwork? result, bool negated = false)
+ {
+ var splitString = value.Trim().Split('/');
+ if (splitString.MoveNext())
+ {
+ var ipBlock = splitString.Current;
+ var address = IPAddress.None;
+ if (negated && ipBlock.StartsWith("!") && IPAddress.TryParse(ipBlock[1..], out var tmpAddress))
+ {
+ address = tmpAddress;
+ }
+ else if (!negated && IPAddress.TryParse(ipBlock, out tmpAddress))
+ {
+ address = tmpAddress;
+ }
+
+ if (address != IPAddress.None)
+ {
+ if (splitString.MoveNext())
{
- IPNetAddress host = new IPNetAddress(addr)
+ var subnetBlock = splitString.Current;
+ if (int.TryParse(subnetBlock, out var netmask))
{
- Tag = i.Tag
- };
-
- res.AddItem(host);
+ result = new IPNetwork(address, netmask);
+ return true;
+ }
+ else if (IPAddress.TryParse(subnetBlock, out var netmaskAddress))
+ {
+ result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress));
+ return true;
+ }
}
- }
- }
-
- return res;
- }
-
- ///
- /// Excludes all the items from this list that are found in excludeList.
- ///
- /// The .
- /// Items to exclude.
- /// Collection is a network collection.
- /// A new collection, with the items excluded.
- public static Collection Exclude(this Collection source, Collection excludeList, bool isNetwork)
- {
- if (source.Count == 0 || excludeList is null)
- {
- return new Collection(source);
- }
-
- Collection results = new Collection();
-
- bool found;
- foreach (var outer in source)
- {
- found = false;
-
- foreach (var inner in excludeList)
- {
- if (outer.Equals(inner))
+ else if (address.AddressFamily == AddressFamily.InterNetwork)
{
- found = true;
- break;
+ result = new IPNetwork(address, 32);
+ return true;
+ }
+ else if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ result = new IPNetwork(address, 128);
+ return true;
}
- }
-
- if (!found)
- {
- results.AddItem(outer, isNetwork);
}
}
- return results;
+ result = null;
+ return false;
}
///
- /// Returns all items that co-exist in this object and target.
+ /// Attempts to parse a host span.
///
- /// The .
- /// Collection to compare with.
- /// A collection containing all the matches.
- public static Collection ThatAreContainedInNetworks(this Collection source, Collection target)
+ /// Host name to parse.
+ /// Object representing the span, if it has successfully been parsed.
+ /// true if IPv4 is enabled.
+ /// true if IPv6 is enabled.
+ /// true if the parsing is successful, false if not.
+ public static bool TryParseHost(ReadOnlySpan host, [NotNullWhen(true)] out IPAddress[]? addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false)
{
- if (source.Count == 0)
+ if (host.IsEmpty)
{
- return new Collection();
+ addresses = null;
+ return false;
}
- ArgumentNullException.ThrowIfNull(target);
+ host = host.Trim();
- Collection nc = new Collection();
-
- foreach (IPObject i in source)
+ // See if it's an IPv6 with port address e.g. [::1] or [::1]:120.
+ if (host[0] == '[')
{
- if (target.ContainsAddress(i))
+ int i = host.IndexOf("]", StringComparison.Ordinal);
+ if (i != -1)
{
- nc.AddItem(i);
+ return TryParseHost(host[1..(i - 1)], out addresses);
+ }
+
+ addresses = Array.Empty();
+ return false;
+ }
+
+ var hosts = new List();
+ foreach (var splitSpan in host.Split(':'))
+ {
+ hosts.Add(splitSpan.ToString());
+ }
+
+ if (hosts.Count <= 2)
+ {
+ // Is hostname or hostname:port
+ if (_fqdnRegex.IsMatch(hosts[0]))
+ {
+ try
+ {
+ addresses = Dns.GetHostAddresses(hosts[0]);
+ return true;
+ }
+ catch (SocketException)
+ {
+ // Log and then ignore socket errors, as the result value will just be an empty array.
+ Console.WriteLine("GetHostAddresses failed.");
+ }
+ }
+
+ // Is an IP4 or IP4:port
+ if (IPAddress.TryParse(hosts[0].AsSpan().LeftPart('/'), out var address))
+ {
+ if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIPv4Enabled && isIPv6Enabled))
+ || ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIPv4Enabled && !isIPv6Enabled)))
+ {
+ addresses = Array.Empty();
+ return false;
+ }
+
+ addresses = new[] { address };
+
+ // Host name is an ip4 address, so fake resolve.
+ return true;
+ }
+ }
+ else if (hosts.Count > 0 && hosts.Count <= 9) // 8 octets + port
+ {
+ if (IPAddress.TryParse(host.LeftPart('/'), out var address))
+ {
+ addresses = new[] { address };
+ return true;
}
}
- return nc;
+ addresses = Array.Empty();
+ return false;
+ }
+
+ ///
+ /// Gets the broadcast address for a .
+ ///
+ /// The .
+ /// The broadcast address.
+ public static IPAddress GetBroadcastAddress(IPNetwork network)
+ {
+ var addressBytes = network.Prefix.GetAddressBytes();
+ if (BitConverter.IsLittleEndian)
+ {
+ addressBytes.Reverse();
+ }
+
+ uint iPAddress = BitConverter.ToUInt32(addressBytes, 0);
+ uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0);
+ uint broadCastIPAddress = iPAddress | ~ipMaskV4;
+
+ return new IPAddress(BitConverter.GetBytes(broadCastIPAddress));
}
}
}
diff --git a/MediaBrowser.Controller/IServerApplicationHost.cs b/MediaBrowser.Controller/IServerApplicationHost.cs
index 11afdc4aed..45ac5c3a85 100644
--- a/MediaBrowser.Controller/IServerApplicationHost.cs
+++ b/MediaBrowser.Controller/IServerApplicationHost.cs
@@ -4,7 +4,6 @@
using System.Net;
using MediaBrowser.Common;
-using MediaBrowser.Common.Net;
using MediaBrowser.Model.System;
using Microsoft.AspNetCore.Http;
@@ -75,10 +74,10 @@ namespace MediaBrowser.Controller
///
/// Gets an URL that can be used to access the API over LAN.
///
- /// An optional hostname to use.
+ /// An optional IP address to use.
/// A value indicating whether to allow HTTPS.
/// The API URL.
- string GetApiUrlForLocalAccess(IPObject hostname = null, bool allowHttps = true);
+ string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true);
///
/// Gets a local (LAN) URL that can be used to access the API.
diff --git a/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs b/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs
index 987a3a908f..c7489d57ae 100644
--- a/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs
+++ b/MediaBrowser.Model/Dlna/UpnpDeviceInfo.cs
@@ -13,10 +13,10 @@ namespace MediaBrowser.Model.Dlna
public Dictionary Headers { get; set; }
- public IPAddress LocalIpAddress { get; set; }
+ public IPAddress LocalIPAddress { get; set; }
public int LocalPort { get; set; }
- public IPAddress RemoteIpAddress { get; set; }
+ public IPAddress RemoteIPAddress { get; set; }
}
}
diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj
index 9a58044853..58ba83a35f 100644
--- a/MediaBrowser.Model/MediaBrowser.Model.csproj
+++ b/MediaBrowser.Model/MediaBrowser.Model.csproj
@@ -33,6 +33,7 @@
+
diff --git a/MediaBrowser.Model/Net/IPData.cs b/MediaBrowser.Model/Net/IPData.cs
new file mode 100644
index 0000000000..985b16c6e4
--- /dev/null
+++ b/MediaBrowser.Model/Net/IPData.cs
@@ -0,0 +1,74 @@
+using System.Net;
+using System.Net.Sockets;
+using Microsoft.AspNetCore.HttpOverrides;
+
+namespace MediaBrowser.Model.Net;
+
+///
+/// Base network object class.
+///
+public class IPData
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The .
+ /// The .
+ /// The interface name.
+ public IPData(IPAddress address, IPNetwork? subnet, string name)
+ {
+ Address = address;
+ Subnet = subnet ?? (address.AddressFamily == AddressFamily.InterNetwork ? new IPNetwork(address, 32) : new IPNetwork(address, 128));
+ Name = name;
+ }
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The .
+ /// The .
+ public IPData(IPAddress address, IPNetwork? subnet)
+ : this(address, subnet, string.Empty)
+ {
+ }
+
+ ///
+ /// Gets or sets the object's IP address.
+ ///
+ public IPAddress Address { get; set; }
+
+ ///
+ /// Gets or sets the object's IP address.
+ ///
+ public IPNetwork Subnet { get; set; }
+
+ ///
+ /// Gets or sets the interface index.
+ ///
+ public int Index { get; set; }
+
+ ///
+ /// Gets or sets the interface name.
+ ///
+ public string Name { get; set; }
+
+ ///
+ /// Gets the AddressFamily of the object.
+ ///
+ public AddressFamily AddressFamily
+ {
+ get
+ {
+ if (Address.Equals(IPAddress.None))
+ {
+ return Subnet.Prefix.AddressFamily.Equals(IPAddress.None)
+ ? AddressFamily.Unspecified
+ : Subnet.Prefix.AddressFamily;
+ }
+ else
+ {
+ return Address.AddressFamily;
+ }
+ }
+ }
+}
diff --git a/MediaBrowser.Model/Net/ISocket.cs b/MediaBrowser.Model/Net/ISocket.cs
deleted file mode 100644
index 3de41d565a..0000000000
--- a/MediaBrowser.Model/Net/ISocket.cs
+++ /dev/null
@@ -1,34 +0,0 @@
-#pragma warning disable CS1591
-
-using System;
-using System.Net;
-using System.Threading;
-using System.Threading.Tasks;
-
-namespace MediaBrowser.Model.Net
-{
- ///
- /// Provides a common interface across platforms for UDP sockets used by this SSDP implementation.
- ///
- public interface ISocket : IDisposable
- {
- IPAddress LocalIPAddress { get; }
-
- Task ReceiveAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);
-
- IAsyncResult BeginReceive(byte[] buffer, int offset, int count, AsyncCallback callback);
-
- SocketReceiveResult EndReceive(IAsyncResult result);
-
- ///
- /// Sends a UDP message to a particular end point (uni or multicast).
- ///
- /// An array of type that contains the data to send.
- /// The zero-based position in buffer at which to begin sending data.
- /// The number of bytes to send.
- /// An that represents the remote device.
- /// The cancellation token to cancel operation.
- /// The task object representing the asynchronous operation.
- Task SendToAsync(byte[] buffer, int offset, int bytes, IPEndPoint endPoint, CancellationToken cancellationToken);
- }
-}
diff --git a/MediaBrowser.Model/Net/ISocketFactory.cs b/MediaBrowser.Model/Net/ISocketFactory.cs
index a2835b711b..128034eb8f 100644
--- a/MediaBrowser.Model/Net/ISocketFactory.cs
+++ b/MediaBrowser.Model/Net/ISocketFactory.cs
@@ -1,31 +1,35 @@
-#pragma warning disable CS1591
-
using System.Net;
+using System.Net.Sockets;
-namespace MediaBrowser.Model.Net
+namespace MediaBrowser.Model.Net;
+
+///
+/// Implemented by components that can create specific socket configurations.
+///
+public interface ISocketFactory
{
///
- /// Implemented by components that can create a platform specific UDP socket implementation, and wrap it in the cross platform interface.
+ /// Creates a new unicast socket using the specified local port number.
///
- public interface ISocketFactory
- {
- ISocket CreateUdpBroadcastSocket(int localPort);
+ /// The local port to bind to.
+ /// A new unicast socket using the specified local port number.
+ Socket CreateUdpBroadcastSocket(int localPort);
- ///
- /// Creates a new unicast socket using the specified local port number.
- ///
- /// The local IP address to bind to.
- /// The local port to bind to.
- /// A new unicast socket using the specified local port number.
- ISocket CreateSsdpUdpSocket(IPAddress localIp, int localPort);
+ ///
+ /// Creates a new unicast socket using the specified local port number.
+ ///
+ /// The bind interface.
+ /// The local port to bind to.
+ /// A new unicast socket using the specified local port number.
+ Socket CreateSsdpUdpSocket(IPData bindInterface, int localPort);
- ///
- /// Creates a new multicast socket using the specified multicast IP address, multicast time to live and local port.
- ///
- /// The multicast IP address to bind to.
- /// The multicast time to live value. Actually a maximum number of network hops for UDP packets.
- /// The local port to bind to.
- /// A implementation.
- ISocket CreateUdpMulticastSocket(IPAddress ipAddress, int multicastTimeToLive, int localPort);
- }
+ ///
+ /// Creates a new multicast socket using the specified multicast IP address, multicast time to live and local port.
+ ///
+ /// The multicast IP address to bind to.
+ /// The bind interface.
+ /// The multicast time to live value. Actually a maximum number of network hops for UDP packets.
+ /// The local port to bind to.
+ /// A new multicast socket using the specfied bind interface, multicast address, multicast time to live and port.
+ Socket CreateUdpMulticastSocket(IPAddress multicastAddress, IPData bindInterface, int multicastTimeToLive, int localPort);
}
diff --git a/RSSDP/DeviceAvailableEventArgs.cs b/RSSDP/DeviceAvailableEventArgs.cs
index 9d477ea9f4..f933f258be 100644
--- a/RSSDP/DeviceAvailableEventArgs.cs
+++ b/RSSDP/DeviceAvailableEventArgs.cs
@@ -8,7 +8,7 @@ namespace Rssdp
///
public sealed class DeviceAvailableEventArgs : EventArgs
{
- public IPAddress RemoteIpAddress { get; set; }
+ public IPAddress RemoteIPAddress { get; set; }
private readonly DiscoveredSsdpDevice _DiscoveredDevice;
diff --git a/RSSDP/ISsdpCommunicationsServer.cs b/RSSDP/ISsdpCommunicationsServer.cs
index 3cbc991d60..95b0a1c704 100644
--- a/RSSDP/ISsdpCommunicationsServer.cs
+++ b/RSSDP/ISsdpCommunicationsServer.cs
@@ -23,23 +23,23 @@ namespace Rssdp.Infrastructure
///
/// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications.
///
- void BeginListeningForBroadcasts();
+ void BeginListeningForMulticast();
///
/// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications.
///
- void StopListeningForBroadcasts();
+ void StopListeningForMulticast();
///
/// Sends a message to a particular address (uni or multicast) and port.
///
- Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken);
+ Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIPAddress, CancellationToken cancellationToken);
///
/// Sends a message to the SSDP multicast address and port.
///
- Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken);
- Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken);
+ Task SendMulticastMessage(string message, IPAddress fromLocalIPAddress, CancellationToken cancellationToken);
+ Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIPAddress, CancellationToken cancellationToken);
///
/// Gets or sets a boolean value indicating whether or not this instance is shared amongst multiple and/or instances.
diff --git a/RSSDP/RequestReceivedEventArgs.cs b/RSSDP/RequestReceivedEventArgs.cs
index 5cf74bd757..b8b2249e42 100644
--- a/RSSDP/RequestReceivedEventArgs.cs
+++ b/RSSDP/RequestReceivedEventArgs.cs
@@ -13,16 +13,16 @@ namespace Rssdp.Infrastructure
private readonly IPEndPoint _ReceivedFrom;
- public IPAddress LocalIpAddress { get; private set; }
+ public IPAddress LocalIPAddress { get; private set; }
///
/// Full constructor.
///
- public RequestReceivedEventArgs(HttpRequestMessage message, IPEndPoint receivedFrom, IPAddress localIpAddress)
+ public RequestReceivedEventArgs(HttpRequestMessage message, IPEndPoint receivedFrom, IPAddress localIPAddress)
{
_Message = message;
_ReceivedFrom = receivedFrom;
- LocalIpAddress = localIpAddress;
+ LocalIPAddress = localIPAddress;
}
///
diff --git a/RSSDP/ResponseReceivedEventArgs.cs b/RSSDP/ResponseReceivedEventArgs.cs
index 93262a4608..e87ba14524 100644
--- a/RSSDP/ResponseReceivedEventArgs.cs
+++ b/RSSDP/ResponseReceivedEventArgs.cs
@@ -9,7 +9,7 @@ namespace Rssdp.Infrastructure
///
public sealed class ResponseReceivedEventArgs : EventArgs
{
- public IPAddress LocalIpAddress { get; set; }
+ public IPAddress LocalIPAddress { get; set; }
private readonly HttpResponseMessage _Message;
diff --git a/RSSDP/SsdpCommunicationsServer.cs b/RSSDP/SsdpCommunicationsServer.cs
index 6e4f5634da..0dce6c3bfa 100644
--- a/RSSDP/SsdpCommunicationsServer.cs
+++ b/RSSDP/SsdpCommunicationsServer.cs
@@ -25,18 +25,18 @@ namespace Rssdp.Infrastructure
* Since stopping the service would be a bad idea (might not be allowed security wise and might
* break other apps running on the system) the only other work around is to use two sockets.
*
- * We use one socket to listen for/receive notifications and search requests (_BroadcastListenSocket).
- * We use a second socket, bound to a different local port, to send search requests and listen for
- * responses (_SendSocket). The responses are sent to the local port this socket is bound to,
- * which isn't port 1900 so the MS service doesn't steal them. While the caller can specify a local
+ * We use one group of sockets to listen for/receive notifications and search requests (_MulticastListenSockets).
+ * We use a second group, bound to a different local port, to send search requests and listen for
+ * responses (_SendSockets). The responses are sent to the local ports these sockets are bound to,
+ * which aren't port 1900 so the MS service doesn't steal them. While the caller can specify a local
* port to use, we will default to 0 which allows the underlying system to auto-assign a free port.
*/
private object _BroadcastListenSocketSynchroniser = new object();
- private ISocket _BroadcastListenSocket;
+ private List _MulticastListenSockets;
private object _SendSocketSynchroniser = new object();
- private List _sendSockets;
+ private List _sendSockets;
private HttpRequestParser _RequestParser;
private HttpResponseParser _ResponseParser;
@@ -78,7 +78,7 @@ namespace Rssdp.Infrastructure
/// The argument is less than or equal to zero.
public SsdpCommunicationsServer(ISocketFactory socketFactory, int localPort, int multicastTimeToLive, INetworkManager networkManager, ILogger logger, bool enableMultiSocketBinding)
{
- if (socketFactory == null)
+ if (socketFactory is null)
{
throw new ArgumentNullException(nameof(socketFactory));
}
@@ -107,28 +107,25 @@ namespace Rssdp.Infrastructure
/// Causes the server to begin listening for multicast messages, being SSDP search requests and notifications.
///
/// Thrown if the property is true (because has been called previously).
- public void BeginListeningForBroadcasts()
+ public void BeginListeningForMulticast()
{
ThrowIfDisposed();
- if (_BroadcastListenSocket == null)
+ lock (_BroadcastListenSocketSynchroniser)
{
- lock (_BroadcastListenSocketSynchroniser)
+ if (_MulticastListenSockets is null)
{
- if (_BroadcastListenSocket == null)
+ try
{
- 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");
- }
+ _MulticastListenSockets = CreateMulticastSocketsAndListen();
+ }
+ catch (SocketException ex)
+ {
+ _logger.LogError("Failed to bind to multicast address: {Message}. DLNA will be unavailable", ex.Message);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error in BeginListeningForMulticast");
}
}
}
@@ -138,15 +135,19 @@ namespace Rssdp.Infrastructure
/// Causes the server to stop listening for multicast messages, being SSDP search requests and notifications.
///
/// Thrown if the property is true (because has been called previously).
- public void StopListeningForBroadcasts()
+ public void StopListeningForMulticast()
{
lock (_BroadcastListenSocketSynchroniser)
{
- if (_BroadcastListenSocket != null)
+ if (_MulticastListenSockets is not null)
{
_logger.LogInformation("{0} disposing _BroadcastListenSocket", GetType().Name);
- _BroadcastListenSocket.Dispose();
- _BroadcastListenSocket = null;
+ foreach (var socket in _MulticastListenSockets)
+ {
+ socket.Dispose();
+ }
+
+ _MulticastListenSockets = null;
}
}
}
@@ -154,16 +155,16 @@ namespace Rssdp.Infrastructure
///
/// Sends a message to a particular address (uni or multicast) and port.
///
- public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken)
+ public async Task SendMessage(byte[] messageData, IPEndPoint destination, IPAddress fromlocalIPAddress, CancellationToken cancellationToken)
{
- if (messageData == null)
+ if (messageData is null)
{
throw new ArgumentNullException(nameof(messageData));
}
ThrowIfDisposed();
- var sockets = GetSendSockets(fromLocalIpAddress, destination);
+ var sockets = GetSendSockets(fromlocalIPAddress, destination);
if (sockets.Count == 0)
{
@@ -180,11 +181,11 @@ namespace Rssdp.Infrastructure
}
}
- private async Task SendFromSocket(ISocket socket, byte[] messageData, IPEndPoint destination, CancellationToken cancellationToken)
+ private async Task SendFromSocket(Socket socket, byte[] messageData, IPEndPoint destination, CancellationToken cancellationToken)
{
try
{
- await socket.SendToAsync(messageData, 0, messageData.Length, destination, cancellationToken).ConfigureAwait(false);
+ await socket.SendToAsync(messageData, destination, cancellationToken).ConfigureAwait(false);
}
catch (ObjectDisposedException)
{
@@ -194,37 +195,42 @@ namespace Rssdp.Infrastructure
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error sending socket message from {0} to {1}", socket.LocalIPAddress.ToString(), destination.ToString());
+ var localIP = ((IPEndPoint)socket.LocalEndPoint).Address;
+ _logger.LogError(ex, "Error sending socket message from {0} to {1}", localIP.ToString(), destination.ToString());
}
}
- private List GetSendSockets(IPAddress fromLocalIpAddress, IPEndPoint destination)
+ private List GetSendSockets(IPAddress fromlocalIPAddress, IPEndPoint destination)
{
EnsureSendSocketCreated();
lock (_SendSocketSynchroniser)
{
- var sockets = _sendSockets.Where(i => i.LocalIPAddress.AddressFamily == fromLocalIpAddress.AddressFamily);
+ var sockets = _sendSockets.Where(s => s.AddressFamily == fromlocalIPAddress.AddressFamily);
// Send from the Any socket and the socket with the matching address
- if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetwork)
+ if (fromlocalIPAddress.AddressFamily == AddressFamily.InterNetwork)
{
- sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.Any) || fromLocalIpAddress.Equals(i.LocalIPAddress));
+ sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any)
+ || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromlocalIPAddress));
// If sending to the loopback address, filter the socket list as well
if (destination.Address.Equals(IPAddress.Loopback))
{
- sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.Any) || i.LocalIPAddress.Equals(IPAddress.Loopback));
+ sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Any)
+ || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.Loopback));
}
}
- else if (fromLocalIpAddress.AddressFamily == AddressFamily.InterNetworkV6)
+ else if (fromlocalIPAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
- sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.IPv6Any) || fromLocalIpAddress.Equals(i.LocalIPAddress));
+ sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any)
+ || ((IPEndPoint)s.LocalEndPoint).Address.Equals(fromlocalIPAddress));
// If sending to the loopback address, filter the socket list as well
if (destination.Address.Equals(IPAddress.IPv6Loopback))
{
- sockets = sockets.Where(i => i.LocalIPAddress.Equals(IPAddress.IPv6Any) || i.LocalIPAddress.Equals(IPAddress.IPv6Loopback));
+ sockets = sockets.Where(s => ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Any)
+ || ((IPEndPoint)s.LocalEndPoint).Address.Equals(IPAddress.IPv6Loopback));
}
}
@@ -232,17 +238,17 @@ namespace Rssdp.Infrastructure
}
}
- public Task SendMulticastMessage(string message, IPAddress fromLocalIpAddress, CancellationToken cancellationToken)
+ public Task SendMulticastMessage(string message, IPAddress fromlocalIPAddress, CancellationToken cancellationToken)
{
- return SendMulticastMessage(message, SsdpConstants.UdpResendCount, fromLocalIpAddress, cancellationToken);
+ return SendMulticastMessage(message, SsdpConstants.UdpResendCount, fromlocalIPAddress, cancellationToken);
}
///
/// Sends a message to the SSDP multicast address and port.
///
- public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromLocalIpAddress, CancellationToken cancellationToken)
+ public async Task SendMulticastMessage(string message, int sendCount, IPAddress fromlocalIPAddress, CancellationToken cancellationToken)
{
- if (message == null)
+ if (message is null)
{
throw new ArgumentNullException(nameof(message));
}
@@ -263,7 +269,7 @@ namespace Rssdp.Infrastructure
new IPEndPoint(
IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress),
SsdpConstants.MulticastPort),
- fromLocalIpAddress,
+ fromlocalIPAddress,
cancellationToken).ConfigureAwait(false);
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
@@ -278,7 +284,7 @@ namespace Rssdp.Infrastructure
{
lock (_SendSocketSynchroniser)
{
- if (_sendSockets != null)
+ if (_sendSockets is not null)
{
var sockets = _sendSockets.ToList();
_sendSockets = null;
@@ -287,7 +293,8 @@ namespace Rssdp.Infrastructure
foreach (var socket in sockets)
{
- _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socket.LocalIPAddress);
+ var socketAddress = ((IPEndPoint)socket.LocalEndPoint).Address;
+ _logger.LogInformation("{0} disposing sendSocket from {1}", GetType().Name, socketAddress);
socket.Dispose();
}
}
@@ -315,20 +322,20 @@ namespace Rssdp.Infrastructure
{
if (disposing)
{
- StopListeningForBroadcasts();
+ StopListeningForMulticast();
StopListeningForResponses();
}
}
- private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromLocalIpAddress, CancellationToken cancellationToken)
+ private Task SendMessageIfSocketNotDisposed(byte[] messageData, IPEndPoint destination, IPAddress fromlocalIPAddress, CancellationToken cancellationToken)
{
var sockets = _sendSockets;
- if (sockets != null)
+ if (sockets is not null)
{
sockets = sockets.ToList();
- var tasks = sockets.Where(s => (fromLocalIpAddress == null || fromLocalIpAddress.Equals(s.LocalIPAddress)))
+ var tasks = sockets.Where(s => (fromlocalIPAddress is null || fromlocalIPAddress.Equals(((IPEndPoint)s.LocalEndPoint).Address)))
.Select(s => SendFromSocket(s, messageData, destination, cancellationToken));
return Task.WhenAll(tasks);
}
@@ -336,50 +343,78 @@ namespace Rssdp.Infrastructure
return Task.CompletedTask;
}
- private ISocket ListenForBroadcastsAsync()
+ private List CreateMulticastSocketsAndListen()
{
- var socket = _SocketFactory.CreateUdpMulticastSocket(IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress), _MulticastTtl, SsdpConstants.MulticastPort);
- _ = ListenToSocketInternal(socket);
-
- return socket;
- }
-
- private List CreateSocketAndListenForResponsesAsync()
- {
- var sockets = new List();
-
- sockets.Add(_SocketFactory.CreateSsdpUdpSocket(IPAddress.Any, _LocalPort));
-
+ var sockets = new List();
+ var multicastGroupAddress = IPAddress.Parse(SsdpConstants.MulticastLocalAdminAddress);
if (_enableMultiSocketBinding)
{
- foreach (var address in _networkManager.GetInternalBindAddresses())
- {
- if (address.AddressFamily == AddressFamily.InterNetworkV6)
- {
- // Not support IPv6 right now
- continue;
- }
+ // IPv6 is currently unsupported
+ var validInterfaces = _networkManager.GetInternalBindAddresses()
+ .Where(x => x.Address is not null)
+ .Where(x => x.AddressFamily == AddressFamily.InterNetwork)
+ .DistinctBy(x => x.Index);
+ foreach (var intf in validInterfaces)
+ {
try
{
- sockets.Add(_SocketFactory.CreateSsdpUdpSocket(address.Address, _LocalPort));
+ var socket = _SocketFactory.CreateUdpMulticastSocket(multicastGroupAddress, intf, _MulticastTtl, SsdpConstants.MulticastPort);
+ _ = ListenToSocketInternal(socket);
+ sockets.Add(socket);
}
catch (Exception ex)
{
- _logger.LogError(ex, "Error in CreateSsdpUdpSocket. IPAddress: {0}", address);
+ _logger.LogError(ex, "Error in CreateMulticastSocketsAndListen. IP address: {0}", intf.Address);
}
}
}
-
- foreach (var socket in sockets)
+ else
{
+ var socket = _SocketFactory.CreateUdpMulticastSocket(multicastGroupAddress, new IPData(IPAddress.Any, null), _MulticastTtl, SsdpConstants.MulticastPort);
_ = ListenToSocketInternal(socket);
+ sockets.Add(socket);
}
return sockets;
}
- private async Task ListenToSocketInternal(ISocket socket)
+ private List CreateSendSockets()
+ {
+ var sockets = new List();
+ if (_enableMultiSocketBinding)
+ {
+ // IPv6 is currently unsupported
+ var validInterfaces = _networkManager.GetInternalBindAddresses()
+ .Where(x => x.Address is not null)
+ .Where(x => x.AddressFamily == AddressFamily.InterNetwork);
+
+ foreach (var intf in validInterfaces)
+ {
+ try
+ {
+ var socket = _SocketFactory.CreateSsdpUdpSocket(intf, _LocalPort);
+ _ = ListenToSocketInternal(socket);
+ sockets.Add(socket);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error in CreateSsdpUdpSocket. IPAddress: {0}", intf.Address);
+ }
+ }
+ }
+ else
+ {
+ var socket = _SocketFactory.CreateSsdpUdpSocket(new IPData(IPAddress.Any, null), _LocalPort);
+ _ = ListenToSocketInternal(socket);
+ sockets.Add(socket);
+ }
+
+
+ return sockets;
+ }
+
+ private async Task ListenToSocketInternal(Socket socket)
{
var cancelled = false;
var receiveBuffer = new byte[8192];
@@ -388,14 +423,17 @@ namespace Rssdp.Infrastructure
{
try
{
- var result = await socket.ReceiveAsync(receiveBuffer, 0, receiveBuffer.Length, CancellationToken.None).ConfigureAwait(false);
+ var result = await socket.ReceiveMessageFromAsync(receiveBuffer, SocketFlags.None, new IPEndPoint(IPAddress.Any, 0), CancellationToken.None).ConfigureAwait(false);;
if (result.ReceivedBytes > 0)
{
- // Strange cannot convert compiler error here if I don't explicitly
- // assign or cast to Action first. Assignment is easier to read,
- // so went with that.
- ProcessMessage(UTF8Encoding.UTF8.GetString(result.Buffer, 0, result.ReceivedBytes), result.RemoteEndPoint, result.LocalIPAddress);
+ var remoteEndpoint = (IPEndPoint)result.RemoteEndPoint;
+ var localEndpointAdapter = _networkManager.GetAllBindInterfaces().First(a => a.Index == result.PacketInformation.Interface);
+
+ ProcessMessage(
+ UTF8Encoding.UTF8.GetString(receiveBuffer, 0, result.ReceivedBytes),
+ remoteEndpoint,
+ localEndpointAdapter.Address);
}
}
catch (ObjectDisposedException)
@@ -411,21 +449,22 @@ namespace Rssdp.Infrastructure
private void EnsureSendSocketCreated()
{
- if (_sendSockets == null)
+ if (_sendSockets is null)
{
lock (_SendSocketSynchroniser)
{
- _sendSockets ??= CreateSocketAndListenForResponsesAsync();
+ _sendSockets ??= CreateSendSockets();
}
}
}
- private void ProcessMessage(string data, IPEndPoint endPoint, IPAddress receivedOnLocalIpAddress)
+ private void ProcessMessage(string data, IPEndPoint endPoint, IPAddress receivedOnlocalIPAddress)
{
// Responses start with the HTTP version, prefixed with HTTP/ while
// requests start with a method which can vary and might be one we haven't
// seen/don't know. We'll check if this message is a request or a response
// by checking for the HTTP/ prefix on the start of the message.
+ _logger.LogDebug("Received data from {From} on {Port} at {Address}:\n{Data}", endPoint.Address, endPoint.Port, receivedOnlocalIPAddress, data);
if (data.StartsWith("HTTP/", StringComparison.OrdinalIgnoreCase))
{
HttpResponseMessage responseMessage = null;
@@ -438,9 +477,9 @@ namespace Rssdp.Infrastructure
// Ignore invalid packets.
}
- if (responseMessage != null)
+ if (responseMessage is not null)
{
- OnResponseReceived(responseMessage, endPoint, receivedOnLocalIpAddress);
+ OnResponseReceived(responseMessage, endPoint, receivedOnlocalIPAddress);
}
}
else
@@ -455,14 +494,14 @@ namespace Rssdp.Infrastructure
// Ignore invalid packets.
}
- if (requestMessage != null)
+ if (requestMessage is not null)
{
- OnRequestReceived(requestMessage, endPoint, receivedOnLocalIpAddress);
+ OnRequestReceived(requestMessage, endPoint, receivedOnlocalIPAddress);
}
}
}
- private void OnRequestReceived(HttpRequestMessage data, IPEndPoint remoteEndPoint, IPAddress receivedOnLocalIpAddress)
+ private void OnRequestReceived(HttpRequestMessage data, IPEndPoint remoteEndPoint, IPAddress receivedOnlocalIPAddress)
{
// SSDP specification says only * is currently used but other uri's might
// be implemented in the future and should be ignored unless understood.
@@ -473,20 +512,20 @@ namespace Rssdp.Infrastructure
}
var handlers = this.RequestReceived;
- if (handlers != null)
+ if (handlers is not null)
{
- handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnLocalIpAddress));
+ handlers(this, new RequestReceivedEventArgs(data, remoteEndPoint, receivedOnlocalIPAddress));
}
}
- private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIpAddress)
+ private void OnResponseReceived(HttpResponseMessage data, IPEndPoint endPoint, IPAddress localIPAddress)
{
var handlers = this.ResponseReceived;
- if (handlers != null)
+ if (handlers is not null)
{
handlers(this, new ResponseReceivedEventArgs(data, endPoint)
{
- LocalIpAddress = localIpAddress
+ LocalIPAddress = localIPAddress
});
}
}
diff --git a/RSSDP/SsdpConstants.cs b/RSSDP/SsdpConstants.cs
index 798f050e1c..442f2b8f84 100644
--- a/RSSDP/SsdpConstants.cs
+++ b/RSSDP/SsdpConstants.cs
@@ -26,6 +26,8 @@ namespace Rssdp.Infrastructure
internal const string SsdpDeviceDescriptionXmlNamespace = "urn:schemas-upnp-org:device-1-0";
+ internal const string ServerVersion = "1.0";
+
///
/// Default buffer size for receiving SSDP broadcasts. Value is 8192 (bytes).
///
diff --git a/RSSDP/SsdpDeviceLocator.cs b/RSSDP/SsdpDeviceLocator.cs
index 7afd325819..59f4c5070b 100644
--- a/RSSDP/SsdpDeviceLocator.cs
+++ b/RSSDP/SsdpDeviceLocator.cs
@@ -1,11 +1,11 @@
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
-
namespace Rssdp.Infrastructure
{
///
@@ -19,19 +19,27 @@ namespace Rssdp.Infrastructure
private Timer _BroadcastTimer;
private object _timerLock = new object();
+ private string _OSName;
+
+ private string _OSVersion;
+
private readonly TimeSpan DefaultSearchWaitTime = TimeSpan.FromSeconds(4);
private readonly TimeSpan OneSecond = TimeSpan.FromSeconds(1);
///
/// Default constructor.
///
- public SsdpDeviceLocator(ISsdpCommunicationsServer communicationsServer)
+ public SsdpDeviceLocator(
+ ISsdpCommunicationsServer communicationsServer,
+ string osName,
+ string osVersion)
{
- if (communicationsServer == null)
- {
- throw new ArgumentNullException(nameof(communicationsServer));
- }
+ ArgumentNullException.ThrowIfNull(communicationsServer);
+ ArgumentNullException.ThrowIfNullOrEmpty(osName);
+ ArgumentNullException.ThrowIfNullOrEmpty(osVersion);
+ _OSName = osName;
+ _OSVersion = osVersion;
_CommunicationsServer = communicationsServer;
_CommunicationsServer.ResponseReceived += CommsServer_ResponseReceived;
@@ -72,7 +80,7 @@ namespace Rssdp.Infrastructure
{
lock (_timerLock)
{
- if (_BroadcastTimer == null)
+ if (_BroadcastTimer is null)
{
_BroadcastTimer = new Timer(OnBroadcastTimerCallback, null, dueTime, period);
}
@@ -87,7 +95,7 @@ namespace Rssdp.Infrastructure
{
lock (_timerLock)
{
- if (_BroadcastTimer != null)
+ if (_BroadcastTimer is not null)
{
_BroadcastTimer.Dispose();
_BroadcastTimer = null;
@@ -148,7 +156,7 @@ namespace Rssdp.Infrastructure
private Task SearchAsync(string searchTarget, TimeSpan searchWaitTime, CancellationToken cancellationToken)
{
- if (searchTarget == null)
+ if (searchTarget is null)
{
throw new ArgumentNullException(nameof(searchTarget));
}
@@ -187,7 +195,7 @@ namespace Rssdp.Infrastructure
{
_CommunicationsServer.RequestReceived -= CommsServer_RequestReceived;
_CommunicationsServer.RequestReceived += CommsServer_RequestReceived;
- _CommunicationsServer.BeginListeningForBroadcasts();
+ _CommunicationsServer.BeginListeningForMulticast();
}
///
@@ -211,7 +219,7 @@ namespace Rssdp.Infrastructure
/// Raises the event.
///
///
- protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IpAddress)
+ protected virtual void OnDeviceAvailable(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IPAddress)
{
if (this.IsDisposed)
{
@@ -219,11 +227,11 @@ namespace Rssdp.Infrastructure
}
var handlers = this.DeviceAvailable;
- if (handlers != null)
+ if (handlers is not null)
{
handlers(this, new DeviceAvailableEventArgs(device, isNewDevice)
{
- RemoteIpAddress = IpAddress
+ RemoteIPAddress = IPAddress
});
}
}
@@ -242,7 +250,7 @@ namespace Rssdp.Infrastructure
}
var handlers = this.DeviceUnavailable;
- if (handlers != null)
+ if (handlers is not null)
{
handlers(this, new DeviceUnavailableEventArgs(device, expired));
}
@@ -281,7 +289,7 @@ namespace Rssdp.Infrastructure
var commsServer = _CommunicationsServer;
_CommunicationsServer = null;
- if (commsServer != null)
+ if (commsServer is not null)
{
commsServer.ResponseReceived -= this.CommsServer_ResponseReceived;
commsServer.RequestReceived -= this.CommsServer_RequestReceived;
@@ -289,13 +297,13 @@ namespace Rssdp.Infrastructure
}
}
- private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IPAddress IpAddress)
+ private void AddOrUpdateDiscoveredDevice(DiscoveredSsdpDevice device, IPAddress IPAddress)
{
bool isNewDevice = false;
lock (_Devices)
{
var existingDevice = FindExistingDeviceNotification(_Devices, device.NotificationType, device.Usn);
- if (existingDevice == null)
+ if (existingDevice is null)
{
_Devices.Add(device);
isNewDevice = true;
@@ -307,17 +315,17 @@ namespace Rssdp.Infrastructure
}
}
- DeviceFound(device, isNewDevice, IpAddress);
+ DeviceFound(device, isNewDevice, IPAddress);
}
- private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IpAddress)
+ private void DeviceFound(DiscoveredSsdpDevice device, bool isNewDevice, IPAddress IPAddress)
{
if (!NotificationTypeMatchesFilter(device))
{
return;
}
- OnDeviceAvailable(device, isNewDevice, IpAddress);
+ OnDeviceAvailable(device, isNewDevice, IPAddress);
}
private bool NotificationTypeMatchesFilter(DiscoveredSsdpDevice device)
@@ -329,12 +337,12 @@ namespace Rssdp.Infrastructure
private Task BroadcastDiscoverMessage(string serviceType, TimeSpan mxValue, CancellationToken cancellationToken)
{
+ const string header = "M-SEARCH * HTTP/1.1";
+
var values = new Dictionary(StringComparer.OrdinalIgnoreCase);
values["HOST"] = "239.255.255.250:1900";
- values["USER-AGENT"] = "UPnP/1.0 DLNADOC/1.50 Platinum/1.0.4.2";
- // values["X-EMBY-SERVERID"] = _appHost.SystemId;
-
+ values["USER-AGENT"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion);
values["MAN"] = "\"ssdp:discover\"";
// Search target
@@ -343,14 +351,12 @@ namespace Rssdp.Infrastructure
// Seconds to delay response
values["MX"] = "3";
- var header = "M-SEARCH * HTTP/1.1";
-
var message = BuildMessage(header, values);
return _CommunicationsServer.SendMulticastMessage(message, null, cancellationToken);
}
- private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress IpAddress)
+ private void ProcessSearchResponseMessage(HttpResponseMessage message, IPAddress IPAddress)
{
if (!message.IsSuccessStatusCode)
{
@@ -358,7 +364,7 @@ namespace Rssdp.Infrastructure
}
var location = GetFirstHeaderUriValue("Location", message);
- if (location != null)
+ if (location is not null)
{
var device = new DiscoveredSsdpDevice()
{
@@ -370,11 +376,11 @@ namespace Rssdp.Infrastructure
ResponseHeaders = message.Headers
};
- AddOrUpdateDiscoveredDevice(device, IpAddress);
+ AddOrUpdateDiscoveredDevice(device, IPAddress);
}
}
- private void ProcessNotificationMessage(HttpRequestMessage message, IPAddress IpAddress)
+ private void ProcessNotificationMessage(HttpRequestMessage message, IPAddress IPAddress)
{
if (String.Compare(message.Method.Method, "Notify", StringComparison.OrdinalIgnoreCase) != 0)
{
@@ -384,7 +390,7 @@ namespace Rssdp.Infrastructure
var notificationType = GetFirstHeaderStringValue("NTS", message);
if (String.Compare(notificationType, SsdpConstants.SsdpKeepAliveNotification, StringComparison.OrdinalIgnoreCase) == 0)
{
- ProcessAliveNotification(message, IpAddress);
+ ProcessAliveNotification(message, IPAddress);
}
else if (String.Compare(notificationType, SsdpConstants.SsdpByeByeNotification, StringComparison.OrdinalIgnoreCase) == 0)
{
@@ -392,10 +398,10 @@ namespace Rssdp.Infrastructure
}
}
- private void ProcessAliveNotification(HttpRequestMessage message, IPAddress IpAddress)
+ private void ProcessAliveNotification(HttpRequestMessage message, IPAddress IPAddress)
{
var location = GetFirstHeaderUriValue("Location", message);
- if (location != null)
+ if (location is not null)
{
var device = new DiscoveredSsdpDevice()
{
@@ -407,7 +413,7 @@ namespace Rssdp.Infrastructure
ResponseHeaders = message.Headers
};
- AddOrUpdateDiscoveredDevice(device, IpAddress);
+ AddOrUpdateDiscoveredDevice(device, IPAddress);
}
}
@@ -445,7 +451,7 @@ namespace Rssdp.Infrastructure
if (message.Headers.Contains(headerName))
{
message.Headers.TryGetValues(headerName, out values);
- if (values != null)
+ if (values is not null)
{
retVal = values.FirstOrDefault();
}
@@ -461,7 +467,7 @@ namespace Rssdp.Infrastructure
if (message.Headers.Contains(headerName))
{
message.Headers.TryGetValues(headerName, out values);
- if (values != null)
+ if (values is not null)
{
retVal = values.FirstOrDefault();
}
@@ -477,7 +483,7 @@ namespace Rssdp.Infrastructure
if (request.Headers.Contains(headerName))
{
request.Headers.TryGetValues(headerName, out values);
- if (values != null)
+ if (values is not null)
{
value = values.FirstOrDefault();
}
@@ -494,7 +500,7 @@ namespace Rssdp.Infrastructure
if (response.Headers.Contains(headerName))
{
response.Headers.TryGetValues(headerName, out values);
- if (values != null)
+ if (values is not null)
{
value = values.FirstOrDefault();
}
@@ -506,7 +512,7 @@ namespace Rssdp.Infrastructure
private TimeSpan CacheAgeFromHeader(System.Net.Http.Headers.CacheControlHeaderValue headerValue)
{
- if (headerValue == null)
+ if (headerValue is null)
{
return TimeSpan.Zero;
}
@@ -563,7 +569,7 @@ namespace Rssdp.Infrastructure
}
}
- if (existingDevices != null && existingDevices.Count > 0)
+ if (existingDevices is not null && existingDevices.Count > 0)
{
foreach (var removedDevice in existingDevices)
{
@@ -619,7 +625,7 @@ namespace Rssdp.Infrastructure
private void CommsServer_ResponseReceived(object sender, ResponseReceivedEventArgs e)
{
- ProcessSearchResponseMessage(e.Message, e.LocalIpAddress);
+ ProcessSearchResponseMessage(e.Message, e.LocalIPAddress);
}
private void CommsServer_RequestReceived(object sender, RequestReceivedEventArgs e)
diff --git a/RSSDP/SsdpDevicePublisher.cs b/RSSDP/SsdpDevicePublisher.cs
index be66f5947d..950e6fec86 100644
--- a/RSSDP/SsdpDevicePublisher.cs
+++ b/RSSDP/SsdpDevicePublisher.cs
@@ -4,9 +4,9 @@ using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Net;
+using System.Text;
using System.Threading;
using System.Threading.Tasks;
-using MediaBrowser.Common.Net;
namespace Rssdp.Infrastructure
{
@@ -31,8 +31,6 @@ namespace Rssdp.Infrastructure
private Random _Random;
- private const string ServerVersion = "1.0";
-
///
/// Default constructor.
///
@@ -42,30 +40,9 @@ namespace Rssdp.Infrastructure
string osVersion,
bool sendOnlyMatchedHost)
{
- if (communicationsServer == null)
- {
- throw new ArgumentNullException(nameof(communicationsServer));
- }
-
- if (osName == null)
- {
- throw new ArgumentNullException(nameof(osName));
- }
-
- if (osName.Length == 0)
- {
- throw new ArgumentException("osName cannot be an empty string.", nameof(osName));
- }
-
- if (osVersion == null)
- {
- throw new ArgumentNullException(nameof(osVersion));
- }
-
- if (osVersion.Length == 0)
- {
- throw new ArgumentException("osVersion cannot be an empty string.", nameof(osName));
- }
+ ArgumentNullException.ThrowIfNull(communicationsServer);
+ ArgumentNullException.ThrowIfNullOrEmpty(osName);
+ ArgumentNullException.ThrowIfNullOrEmpty(osVersion);
_SupportPnpRootDevice = true;
_Devices = new List();
@@ -79,10 +56,13 @@ namespace Rssdp.Infrastructure
_OSVersion = osVersion;
_sendOnlyMatchedHost = sendOnlyMatchedHost;
- _CommsServer.BeginListeningForBroadcasts();
+ _CommsServer.BeginListeningForMulticast();
+
+ // Send alive notification once on creation
+ SendAllAliveNotifications(null);
}
- public void StartBroadcastingAliveMessages(TimeSpan interval)
+ public void StartSendingAliveNotifications(TimeSpan interval)
{
_RebroadcastAliveNotificationsTimer = new Timer(SendAllAliveNotifications, null, TimeSpan.FromSeconds(5), interval);
}
@@ -98,10 +78,9 @@ namespace Rssdp.Infrastructure
/// The instance to add.
/// Thrown if the argument is null.
/// Thrown if the contains property values that are not acceptable to the UPnP 1.0 specification.
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "t", Justification = "Capture task to local variable suppresses compiler warning, but task is not really needed.")]
public void AddDevice(SsdpRootDevice device)
{
- if (device == null)
+ if (device is null)
{
throw new ArgumentNullException(nameof(device));
}
@@ -137,7 +116,7 @@ namespace Rssdp.Infrastructure
/// Thrown if the argument is null.
public async Task RemoveDevice(SsdpRootDevice device)
{
- if (device == null)
+ if (device is null)
{
throw new ArgumentNullException(nameof(device));
}
@@ -199,7 +178,7 @@ namespace Rssdp.Infrastructure
DisposeRebroadcastTimer();
var commsServer = _CommsServer;
- if (commsServer != null)
+ if (commsServer is not null)
{
commsServer.RequestReceived -= this.CommsServer_RequestReceived;
}
@@ -208,7 +187,7 @@ namespace Rssdp.Infrastructure
Task.WaitAll(tasks);
_CommsServer = null;
- if (commsServer != null)
+ if (commsServer is not null)
{
if (!commsServer.IsShared)
{
@@ -224,7 +203,7 @@ namespace Rssdp.Infrastructure
string mx,
string searchTarget,
IPEndPoint remoteEndPoint,
- IPAddress receivedOnlocalIpAddress,
+ IPAddress receivedOnlocalIPAddress,
CancellationToken cancellationToken)
{
if (String.IsNullOrEmpty(searchTarget))
@@ -280,27 +259,25 @@ namespace Rssdp.Infrastructure
}
else if (searchTarget.Trim().StartsWith("uuid:", StringComparison.OrdinalIgnoreCase))
{
- devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray();
+ devices = GetAllDevicesAsFlatEnumerable().Where(d => String.Compare(d.Uuid, searchTarget.Substring(5), StringComparison.OrdinalIgnoreCase) == 0).ToArray();
}
else if (searchTarget.StartsWith("urn:", StringComparison.OrdinalIgnoreCase))
{
- devices = (from device in GetAllDevicesAsFlatEnumerable() where String.Compare(device.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0 select device).ToArray();
+ devices = GetAllDevicesAsFlatEnumerable().Where(d => String.Compare(d.FullDeviceType, searchTarget, StringComparison.OrdinalIgnoreCase) == 0).ToArray();
}
}
- if (devices != null)
+ if (devices is not null)
{
- var deviceList = devices.ToList();
// WriteTrace(String.Format("Sending {0} search responses", deviceList.Count));
- foreach (var device in deviceList)
+ foreach (var device in devices)
{
var root = device.ToRootDevice();
- 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(receivedOnlocalIPAddress))
{
- SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIpAddress, cancellationToken);
+ SendDeviceSearchResponses(device, remoteEndPoint, receivedOnlocalIPAddress, cancellationToken);
}
}
}
@@ -315,22 +292,22 @@ namespace Rssdp.Infrastructure
private void SendDeviceSearchResponses(
SsdpDevice device,
IPEndPoint endPoint,
- IPAddress receivedOnlocalIpAddress,
+ IPAddress receivedOnlocalIPAddress,
CancellationToken cancellationToken)
{
- bool isRootDevice = (device as SsdpRootDevice) != null;
+ bool isRootDevice = (device as SsdpRootDevice) is not null;
if (isRootDevice)
{
- SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken);
+ SendSearchResponse(SsdpConstants.UpnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.UpnpDeviceTypeRootDevice), endPoint, receivedOnlocalIPAddress, cancellationToken);
if (this.SupportPnpRootDevice)
{
- SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint, receivedOnlocalIpAddress, cancellationToken);
+ SendSearchResponse(SsdpConstants.PnpDeviceTypeRootDevice, device, GetUsn(device.Udn, SsdpConstants.PnpDeviceTypeRootDevice), endPoint, receivedOnlocalIPAddress, cancellationToken);
}
}
- SendSearchResponse(device.Udn, device, device.Udn, endPoint, receivedOnlocalIpAddress, cancellationToken);
+ SendSearchResponse(device.Udn, device, device.Udn, endPoint, receivedOnlocalIPAddress, cancellationToken);
- SendSearchResponse(device.FullDeviceType, device, GetUsn(device.Udn, device.FullDeviceType), endPoint, receivedOnlocalIpAddress, cancellationToken);
+ SendSearchResponse(device.FullDeviceType, device, GetUsn(device.Udn, device.FullDeviceType), endPoint, receivedOnlocalIPAddress, cancellationToken);
}
private string GetUsn(string udn, string fullDeviceType)
@@ -343,22 +320,20 @@ namespace Rssdp.Infrastructure
SsdpDevice device,
string uniqueServiceName,
IPEndPoint endPoint,
- IPAddress receivedOnlocalIpAddress,
+ IPAddress receivedOnlocalIPAddress,
CancellationToken cancellationToken)
{
- var rootDevice = device.ToRootDevice();
-
- // var additionalheaders = FormatCustomHeadersForResponse(device);
-
const string header = "HTTP/1.1 200 OK";
+ var rootDevice = device.ToRootDevice();
var values = new Dictionary(StringComparer.OrdinalIgnoreCase);
values["EXT"] = "";
values["DATE"] = DateTime.UtcNow.ToString("r");
+ values["HOST"] = "239.255.255.250:1900";
values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds;
values["ST"] = searchTarget;
- values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
+ values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion);
values["USN"] = uniqueServiceName;
values["LOCATION"] = rootDevice.Location.ToString();
@@ -367,9 +342,9 @@ namespace Rssdp.Infrastructure
try
{
await _CommsServer.SendMessage(
- System.Text.Encoding.UTF8.GetBytes(message),
+ Encoding.UTF8.GetBytes(message),
endPoint,
- receivedOnlocalIpAddress,
+ receivedOnlocalIPAddress,
cancellationToken)
.ConfigureAwait(false);
}
@@ -492,7 +467,7 @@ namespace Rssdp.Infrastructure
values["DATE"] = DateTime.UtcNow.ToString("r");
values["CACHE-CONTROL"] = "max-age = " + rootDevice.CacheLifetime.TotalSeconds;
values["LOCATION"] = rootDevice.Location.ToString();
- values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
+ values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion);
values["NTS"] = "ssdp:alive";
values["NT"] = notificationType;
values["USN"] = uniqueServiceName;
@@ -527,7 +502,6 @@ namespace Rssdp.Infrastructure
return Task.WhenAll(tasks);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "byebye", Justification = "Correct value for this type of notification in SSDP.")]
private Task SendByeByeNotification(SsdpDevice device, string notificationType, string uniqueServiceName, CancellationToken cancellationToken)
{
const string header = "NOTIFY * HTTP/1.1";
@@ -537,7 +511,7 @@ namespace Rssdp.Infrastructure
// If needed later for non-server devices, these headers will need to be dynamic
values["HOST"] = "239.255.255.250:1900";
values["DATE"] = DateTime.UtcNow.ToString("r");
- values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, ServerVersion);
+ values["SERVER"] = string.Format(CultureInfo.InvariantCulture, "{0}/{1} UPnP/1.0 RSSDP/{2}", _OSName, _OSVersion, SsdpConstants.ServerVersion);
values["NTS"] = "ssdp:byebye";
values["NT"] = notificationType;
values["USN"] = uniqueServiceName;
@@ -553,7 +527,7 @@ namespace Rssdp.Infrastructure
{
var timer = _RebroadcastAliveNotificationsTimer;
_RebroadcastAliveNotificationsTimer = null;
- if (timer != null)
+ if (timer is not null)
{
timer.Dispose();
}
@@ -578,7 +552,7 @@ namespace Rssdp.Infrastructure
private string GetFirstHeaderValue(System.Net.Http.Headers.HttpRequestHeaders httpRequestHeaders, string headerName)
{
string retVal = null;
- if (httpRequestHeaders.TryGetValues(headerName, out var values) && values != null)
+ if (httpRequestHeaders.TryGetValues(headerName, out var values) && values is not null)
{
retVal = values.FirstOrDefault();
}
@@ -590,7 +564,7 @@ namespace Rssdp.Infrastructure
private void WriteTrace(string text)
{
- if (LogFunction != null)
+ if (LogFunction is not null)
{
LogFunction(text);
}
@@ -600,7 +574,7 @@ namespace Rssdp.Infrastructure
private void WriteTrace(string text, SsdpDevice device)
{
var rootDevice = device as SsdpRootDevice;
- if (rootDevice != null)
+ if (rootDevice is not null)
{
WriteTrace(text + " " + device.DeviceType + " - " + device.Uuid + " - " + rootDevice.Location);
}
@@ -626,7 +600,7 @@ namespace Rssdp.Infrastructure
// else if (!e.Message.Headers.Contains("MAN"))
// WriteTrace("Ignoring search request - missing MAN header.");
// else
- ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom, e.LocalIpAddress, CancellationToken.None);
+ ProcessSearchRequest(GetFirstHeaderValue(e.Message.Headers, "MX"), GetFirstHeaderValue(e.Message.Headers, "ST"), e.ReceivedFrom, e.LocalIPAddress, CancellationToken.None);
}
}
diff --git a/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs b/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs
deleted file mode 100644
index aa2dbc57a2..0000000000
--- a/tests/Jellyfin.Networking.Tests/IPNetAddressTests.cs
+++ /dev/null
@@ -1,49 +0,0 @@
-using FsCheck;
-using FsCheck.Xunit;
-using MediaBrowser.Common.Net;
-using Xunit;
-
-namespace Jellyfin.Networking.Tests
-{
- public static class IPNetAddressTests
- {
- ///
- /// Checks IP address formats.
- ///
- /// IP Address.
- [Theory]
- [InlineData("127.0.0.1")]
- [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517")]
- [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517/56")]
- [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517]")]
- [InlineData("fe80::7add:12ff:febb:c67b%16")]
- [InlineData("[fe80::7add:12ff:febb:c67b%16]:123")]
- [InlineData("fe80::7add:12ff:febb:c67b%16:123")]
- [InlineData("[fe80::7add:12ff:febb:c67b%16]")]
- [InlineData("192.168.1.2/255.255.255.0")]
- [InlineData("192.168.1.2/24")]
- public static void TryParse_ValidIPStrings_True(string address)
- => Assert.True(IPNetAddress.TryParse(address, out _));
-
- [Property]
- public static Property TryParse_IPv4Address_True(IPv4Address address)
- => IPNetAddress.TryParse(address.Item.ToString(), out _).ToProperty();
-
- [Property]
- public static Property TryParse_IPv6Address_True(IPv6Address address)
- => IPNetAddress.TryParse(address.Item.ToString(), out _).ToProperty();
-
- ///
- /// All should be invalid address strings.
- ///
- /// Invalid address strings.
- [Theory]
- [InlineData("256.128.0.0.0.1")]
- [InlineData("127.0.0.1#")]
- [InlineData("localhost!")]
- [InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")]
- [InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")]
- public static void TryParse_InvalidAddressString_False(string address)
- => Assert.False(IPNetAddress.TryParse(address, out _));
- }
-}
diff --git a/tests/Jellyfin.Networking.Tests/IPHostTests.cs b/tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs
similarity index 80%
rename from tests/Jellyfin.Networking.Tests/IPHostTests.cs
rename to tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs
index ec3a1300c8..c81fdefe95 100644
--- a/tests/Jellyfin.Networking.Tests/IPHostTests.cs
+++ b/tests/Jellyfin.Networking.Tests/NetworkExtensionsTests.cs
@@ -5,7 +5,7 @@ using Xunit;
namespace Jellyfin.Networking.Tests
{
- public static class IPHostTests
+ public static class NetworkExtensionsTests
{
///
/// Checks IP address formats.
@@ -27,15 +27,15 @@ namespace Jellyfin.Networking.Tests
[InlineData("192.168.1.2/255.255.255.0")]
[InlineData("192.168.1.2/24")]
public static void TryParse_ValidHostStrings_True(string address)
- => Assert.True(IPHost.TryParse(address, out _));
+ => Assert.True(NetworkExtensions.TryParseHost(address, out _, true, true));
[Property]
public static Property TryParse_IPv4Address_True(IPv4Address address)
- => IPHost.TryParse(address.Item.ToString(), out _).ToProperty();
+ => NetworkExtensions.TryParseHost(address.Item.ToString(), out _, true, true).ToProperty();
[Property]
public static Property TryParse_IPv6Address_True(IPv6Address address)
- => IPHost.TryParse(address.Item.ToString(), out _).ToProperty();
+ => NetworkExtensions.TryParseHost(address.Item.ToString(), out _, true, true).ToProperty();
///
/// All should be invalid address strings.
@@ -48,6 +48,6 @@ namespace Jellyfin.Networking.Tests
[InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")]
[InlineData("[fd23:184f:2029:0:3139:7386:67d7:d517:1231]")]
public static void TryParse_InvalidAddressString_False(string address)
- => Assert.False(IPHost.TryParse(address, out _));
+ => Assert.False(NetworkExtensions.TryParseHost(address, out _, true, true));
}
}
diff --git a/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs
index df2a2ca708..0b07a3c53f 100644
--- a/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs
+++ b/tests/Jellyfin.Networking.Tests/NetworkManagerTests.cs
@@ -23,8 +23,8 @@ namespace Jellyfin.Networking.Tests
var ip = IPAddress.Parse(value);
var conf = new NetworkConfiguration()
{
- EnableIPV6 = true,
- EnableIPV4 = true,
+ EnableIPv6 = true,
+ EnableIPv4 = true,
LocalNetworkSubnets = network.Split(',')
};
@@ -51,8 +51,8 @@ namespace Jellyfin.Networking.Tests
var ip = IPAddress.Parse(value);
var conf = new NetworkConfiguration()
{
- EnableIPV6 = true,
- EnableIPV4 = true,
+ EnableIPv6 = true,
+ EnableIPv4 = true,
LocalNetworkSubnets = network.Split(',')
};
diff --git a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs
index 8174632bb4..77f18c5445 100644
--- a/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs
+++ b/tests/Jellyfin.Networking.Tests/NetworkParseTests.cs
@@ -1,10 +1,12 @@
using System;
-using System.Collections.ObjectModel;
+using System.Collections.Generic;
+using System.Linq;
using System.Net;
using Jellyfin.Networking.Configuration;
using Jellyfin.Networking.Manager;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
+using MediaBrowser.Model.Net;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using Xunit;
@@ -34,6 +36,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.
@@ -44,8 +48,8 @@ namespace Jellyfin.Networking.Tests
{
var conf = new NetworkConfiguration()
{
- EnableIPV6 = true,
- EnableIPV4 = true,
+ EnableIPv6 = true,
+ EnableIPv4 = true,
LocalNetworkSubnets = lan?.Split(';') ?? throw new ArgumentNullException(nameof(lan))
};
@@ -53,162 +57,97 @@ namespace Jellyfin.Networking.Tests
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger());
NetworkManager.MockNetworkSettings = string.Empty;
- Assert.Equal(nm.GetInternalBindAddresses().AsString(), value);
+ Assert.Equal(value, "[" + string.Join(",", nm.GetInternalBindAddresses().Select(x => x.Address + "/" + x.Subnet.PrefixLength)) + "]");
}
///
- /// Test collection parsing.
+ /// Checks valid IP address formats.
///
- /// Collection to parse.
- /// Included addresses from the collection.
- /// Included IP4 addresses from the collection.
- /// Excluded addresses from the collection.
- /// Excluded IP4 addresses from the collection.
- /// Network addresses of the collection.
+ /// IP Address.
[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());
-
- // Test included.
- Collection nc = nm.CreateIPCollection(settings.Split(','), false);
- Assert.Equal(nc.AsString(), result1);
-
- // Test excluded.
- nc = nm.CreateIPCollection(settings.Split(','), true);
- Assert.Equal(nc.AsString(), result3);
-
- conf.EnableIPV6 = false;
- nm.UpdateSettings(conf);
-
- // Test IP4 included.
- nc = nm.CreateIPCollection(settings.Split(','), false);
- Assert.Equal(nc.AsString(), result2);
-
- // Test IP4 excluded.
- nc = nm.CreateIPCollection(settings.Split(','), true);
- Assert.Equal(nc.AsString(), result4);
-
- conf.EnableIPV6 = true;
- nm.UpdateSettings(conf);
-
- // Test network addresses of collection.
- nc = nm.CreateIPCollection(settings.Split(','), false);
- nc = nc.AsNetworks();
- Assert.Equal(nc.AsString(), result5);
- }
+ [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 _));
///
- /// Union two collections.
+ /// Checks invalid IP address formats.
///
- /// Source.
- /// Destination.
- /// Result.
+ /// IP Address.
[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());
-
- Collection nc1 = nm.CreateIPCollection(settings.Split(','), false);
- Collection 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 _));
+ ///
+ /// Checks if IPv4 address is within a defined subnet.
+ ///
+ /// Network mask.
+ /// IP Address.
[Theory]
[InlineData("192.168.5.85/24", "192.168.5.1")]
[InlineData("192.168.5.85/24", "192.168.5.254")]
+ [InlineData("192.168.5.85/255.255.255.0", "192.168.5.254")]
[InlineData("10.128.240.50/30", "10.128.240.48")]
[InlineData("10.128.240.50/30", "10.128.240.49")]
[InlineData("10.128.240.50/30", "10.128.240.50")]
[InlineData("10.128.240.50/30", "10.128.240.51")]
+ [InlineData("10.128.240.50/255.255.255.252", "10.128.240.51")]
[InlineData("127.0.0.1/8", "127.0.0.1")]
- public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress)
+ 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)));
}
+ ///
+ /// Checks if IPv4 address is not within a defined subnet.
+ ///
+ /// Network mask.
+ /// IP Address.
[Theory]
[InlineData("192.168.5.85/24", "192.168.4.254")]
[InlineData("192.168.5.85/24", "191.168.5.254")]
+ [InlineData("192.168.5.85/255.255.255.252", "192.168.4.254")]
[InlineData("10.128.240.50/30", "10.128.240.47")]
[InlineData("10.128.240.50/30", "10.128.240.52")]
[InlineData("10.128.240.50/30", "10.128.239.50")]
[InlineData("10.128.240.50/30", "10.127.240.51")]
- public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress)
+ [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)));
}
+ ///
+ /// Checks if IPv6 address is within a defined subnet.
+ ///
+ /// Network mask.
+ /// IP Address.
[Theory]
[InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")]
[InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFFF")]
[InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0001:0000:0000:0000")]
[InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFF0")]
[InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")]
- public void IpV6SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress)
+ public void IPv6SubnetMaskMatchesValidIPAddress(string netMask, string ipAddress)
{
- 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]
@@ -217,79 +156,16 @@ namespace Jellyfin.Networking.Tests
[InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0001:0000:0000:0000")]
[InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFF0")]
[InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0001")]
- public void IpV6SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress)
+ public void IPv6SubnetMaskDoesNotMatchInvalidIPAddress(string netMask, string ipAddress)
{
- var ipAddressObj = IPNetAddress.Parse(netMask);
- Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
+ Assert.False(NetworkExtensions.TryParseToSubnet(netMask, out var subnet) && subnet.Contains(IPAddress.Parse(ipAddress)));
}
[Theory]
- [InlineData("10.0.0.0/255.0.0.0", "10.10.10.1/32")]
- [InlineData("10.0.0.0/8", "10.10.10.1/32")]
- [InlineData("10.0.0.0/255.0.0.0", "10.10.10.1")]
-
- [InlineData("10.10.0.0/255.255.0.0", "10.10.10.1/32")]
- [InlineData("10.10.0.0/16", "10.10.10.1/32")]
- [InlineData("10.10.0.0/255.255.0.0", "10.10.10.1")]
-
- [InlineData("10.10.10.0/255.255.255.0", "10.10.10.1/32")]
- [InlineData("10.10.10.0/24", "10.10.10.1/32")]
- [InlineData("10.10.10.0/255.255.255.0", "10.10.10.1")]
-
- public void TestSubnetContains(string network, string ip)
- {
- Assert.True(IPNetAddress.TryParse(network, out var networkObj));
- Assert.True(IPNetAddress.TryParse(ip, out var ipObj));
- Assert.True(networkObj.Contains(ipObj));
- }
-
- [Theory]
- [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24", "172.168.1.2/24")]
- [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24, 10.10.10.1", "172.168.1.2/24,10.10.10.1/24")]
- [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/255.255.255.0, 10.10.10.1", "192.168.1.2/24,10.10.10.1/24")]
- [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/24, 100.10.10.1", "192.168.1.2/24")]
- [InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "194.168.1.2/24, 100.10.10.1", "")]
-
- public void TestCollectionEquality(string source, string dest, string result)
- {
- 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());
-
- // Test included, IP6.
- Collection ncSource = nm.CreateIPCollection(source.Split(','));
- Collection ncDest = nm.CreateIPCollection(dest.Split(','));
- Collection ncResult = ncSource.ThatAreContainedInNetworks(ncDest);
- Collection resultCollection = nm.CreateIPCollection(result.Split(','));
- Assert.True(ncResult.Compare(resultCollection));
- }
-
- [Theory]
- [InlineData("10.1.1.1/32", "10.1.1.1")]
- [InlineData("192.168.1.254/32", "192.168.1.254/255.255.255.255")]
-
- public void TestEquals(string source, string dest)
- {
- Assert.True(IPNetAddress.Parse(source).Equals(IPNetAddress.Parse(dest)));
- Assert.True(IPNetAddress.Parse(dest).Equals(IPNetAddress.Parse(source)));
- }
-
- [Theory]
-
// Testing bind interfaces.
// On my system eth16 is internal, eth11 external (Windows defines the indexes).
//
- // This test is to replicate how DNLA requests work throughout the system.
+ // This test is to replicate how DLNA requests work throughout the system.
// User on internal network, we're bound internal and external - so result is internal.
[InlineData("192.168.1.1", "eth16,eth11", false, "eth16")]
@@ -319,23 +195,24 @@ namespace Jellyfin.Networking.Tests
var conf = new NetworkConfiguration()
{
LocalNetworkAddresses = bindAddresses.Split(','),
- EnableIPV6 = ipv6enabled,
- EnableIPV4 = true
+ EnableIPv6 = ipv6enabled,
+ EnableIPv4 = true
};
NetworkManager.MockNetworkSettings = "192.168.1.208/24,-16,eth16|200.200.200.200/24,11,eth11";
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger());
NetworkManager.MockNetworkSettings = string.Empty;
- _ = nm.TryParseInterface(result, out Collection? resultObj);
-
- // Check to see if dns resolution is working. If not, skip test.
- _ = IPHost.TryParse(source, out var host);
-
- if (resultObj is not null && host?.HasAddress == true)
+ // Check to see if DNS resolution is working. If not, skip test.
+ if (!NetworkExtensions.TryParseHost(source, out var host))
{
- result = ((IPNetAddress)resultObj[0]).ToString(true);
- var intf = nm.GetBindInterface(source, out _);
+ return;
+ }
+
+ if (nm.TryParseInterface(result, out var resultObj))
+ {
+ result = resultObj.First().Address.ToString();
+ var intf = nm.GetBindAddress(source, out _);
Assert.Equal(intf, result);
}
@@ -363,8 +240,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")]
@@ -381,8 +258,8 @@ namespace Jellyfin.Networking.Tests
{
LocalNetworkSubnets = lan.Split(','),
LocalNetworkAddresses = bindAddresses.Split(','),
- EnableIPV6 = ipv6enabled,
- EnableIPV4 = true,
+ EnableIPv6 = ipv6enabled,
+ EnableIPv4 = true,
PublishedServerUriBySubnet = new string[] { publishedServers }
};
@@ -390,15 +267,15 @@ namespace Jellyfin.Networking.Tests
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger());
NetworkManager.MockNetworkSettings = string.Empty;
- if (nm.TryParseInterface(result, out Collection? resultObj) && resultObj is not null)
+ if (nm.TryParseInterface(result, out IReadOnlyList? resultObj) && resultObj is not null)
{
- // Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks).
- result = ((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? _);
+ var intf = nm.GetBindAddress(source, out int? _);
- Assert.Equal(intf, result);
+ Assert.Equal(result, intf);
}
[Theory]
@@ -406,39 +283,40 @@ namespace Jellyfin.Networking.Tests
[InlineData("185.10.10.10", "185.10.10.10", false)]
[InlineData("", "100.100.100.100", false)]
- public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIpsInWhitelist(string addresses, string remoteIp, bool denied)
+ public void HasRemoteAccess_GivenWhitelist_AllowsOnlyIPsInWhitelist(string addresses, string remoteIP, bool denied)
{
// Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
// If left blank, all remote addresses will be allowed.
var conf = new NetworkConfiguration()
{
- EnableIPV4 = true,
+ EnableIPv4 = true,
RemoteIPFilter = addresses.Split(','),
IsRemoteIPFilterBlacklist = false
};
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger());
- Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied);
+ Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIP)), denied);
}
[Theory]
[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)
+
+ public void HasRemoteAccess_GivenBlacklist_BlacklistTheIPs(string addresses, string remoteIP, bool denied)
{
// Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
// If left blank, all remote addresses will be allowed.
var conf = new NetworkConfiguration()
{
- EnableIPV4 = true,
+ EnableIPv4 = true,
RemoteIPFilter = addresses.Split(','),
IsRemoteIPFilterBlacklist = true
};
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger());
- Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIp)), denied);
+ Assert.NotEqual(nm.HasRemoteAccess(IPAddress.Parse(remoteIP)), denied);
}
[Theory]
@@ -450,7 +328,7 @@ namespace Jellyfin.Networking.Tests
{
var conf = new NetworkConfiguration
{
- EnableIPV4 = true,
+ EnableIPv4 = true,
LocalNetworkSubnets = lan.Split(','),
LocalNetworkAddresses = bind.Split(',')
};
@@ -458,7 +336,7 @@ namespace Jellyfin.Networking.Tests
NetworkManager.MockNetworkSettings = interfaces;
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger());
- var interfaceToUse = nm.GetBindInterface(string.Empty, out _);
+ var interfaceToUse = nm.GetBindAddress(string.Empty, out _);
Assert.Equal(result, interfaceToUse);
}
@@ -474,7 +352,7 @@ namespace Jellyfin.Networking.Tests
{
var conf = new NetworkConfiguration
{
- EnableIPV4 = true,
+ EnableIPv4 = true,
LocalNetworkSubnets = lan.Split(','),
LocalNetworkAddresses = bind.Split(',')
};
@@ -482,7 +360,7 @@ namespace Jellyfin.Networking.Tests
NetworkManager.MockNetworkSettings = interfaces;
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger());
- var interfaceToUse = nm.GetBindInterface(source, out _);
+ var interfaceToUse = nm.GetBindAddress(source, out _);
Assert.Equal(result, interfaceToUse);
}
diff --git a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs
index a1bdfa31b8..49516ccccd 100644
--- a/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs
+++ b/tests/Jellyfin.Server.Tests/ParseNetworkTests.cs
@@ -21,9 +21,9 @@ namespace Jellyfin.Server.Tests
data.Add(
true,
true,
- new string[] { "192.168.t", "127.0.0.1", "1234.1232.12.1234" },
- new IPAddress[] { IPAddress.Loopback.MapToIPv6() },
- Array.Empty());
+ new string[] { "192.168.t", "127.0.0.1", "::1", "1234.1232.12.1234" },
+ new IPAddress[] { IPAddress.Loopback },
+ new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) });
data.Add(
true,
@@ -64,7 +64,7 @@ namespace Jellyfin.Server.Tests
true,
true,
new string[] { "localhost" },
- new IPAddress[] { IPAddress.Loopback.MapToIPv6() },
+ new IPAddress[] { IPAddress.Loopback },
new IPNetwork[] { new IPNetwork(IPAddress.IPv6Loopback, 128) });
return data;
}
@@ -77,8 +77,8 @@ namespace Jellyfin.Server.Tests
var settings = new NetworkConfiguration
{
- EnableIPV4 = ip4,
- EnableIPV6 = ip6
+ EnableIPv4 = ip4,
+ EnableIPv6 = ip6
};
ForwardedHeadersOptions options = new ForwardedHeadersOptions();
@@ -116,8 +116,8 @@ namespace Jellyfin.Server.Tests
{
var conf = new NetworkConfiguration()
{
- EnableIPV6 = true,
- EnableIPV4 = true,
+ EnableIPv6 = true,
+ EnableIPv4 = true,
};
return new NetworkManager(GetMockConfig(conf), new NullLogger());