Merge pull request #4125 from BaronGreenback/NetworkPR2
Networking 2 (Cumulative PR) - Swapping over to new NetworkManagerpull/4545/head
commit
a57b99bffd
@ -1,566 +0,0 @@
|
|||||||
#pragma warning disable CS1591
|
|
||||||
|
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Net;
|
|
||||||
using System.Net.NetworkInformation;
|
|
||||||
using System.Net.Sockets;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
using MediaBrowser.Common.Net;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
|
|
||||||
namespace Emby.Server.Implementations.Networking
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Class to take care of network interface management.
|
|
||||||
/// </summary>
|
|
||||||
public class NetworkManager : INetworkManager
|
|
||||||
{
|
|
||||||
private readonly ILogger<NetworkManager> _logger;
|
|
||||||
private readonly object _localIpAddressSyncLock = new object();
|
|
||||||
private readonly object _subnetLookupLock = new object();
|
|
||||||
private readonly Dictionary<string, List<string>> _subnetLookup = new Dictionary<string, List<string>>(StringComparer.Ordinal);
|
|
||||||
|
|
||||||
private IPAddress[] _localIpAddresses;
|
|
||||||
|
|
||||||
private List<PhysicalAddress> _macAddresses;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Initializes a new instance of the <see cref="NetworkManager"/> class.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="logger">Logger to use for messages.</param>
|
|
||||||
public NetworkManager(ILogger<NetworkManager> logger)
|
|
||||||
{
|
|
||||||
_logger = logger;
|
|
||||||
|
|
||||||
NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged;
|
|
||||||
NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public event EventHandler NetworkChanged;
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public Func<string[]> LocalSubnetsFn { get; set; }
|
|
||||||
|
|
||||||
private void OnNetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
|
|
||||||
{
|
|
||||||
_logger.LogDebug("NetworkAvailabilityChanged");
|
|
||||||
OnNetworkChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void OnNetworkAddressChanged(object sender, EventArgs e)
|
|
||||||
{
|
|
||||||
_logger.LogDebug("NetworkAddressChanged");
|
|
||||||
OnNetworkChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void OnNetworkChanged()
|
|
||||||
{
|
|
||||||
lock (_localIpAddressSyncLock)
|
|
||||||
{
|
|
||||||
_localIpAddresses = null;
|
|
||||||
_macAddresses = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
NetworkChanged?.Invoke(this, EventArgs.Empty);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public IPAddress[] GetLocalIpAddresses()
|
|
||||||
{
|
|
||||||
lock (_localIpAddressSyncLock)
|
|
||||||
{
|
|
||||||
if (_localIpAddresses == null)
|
|
||||||
{
|
|
||||||
var addresses = GetLocalIpAddressesInternal().ToArray();
|
|
||||||
|
|
||||||
_localIpAddresses = addresses;
|
|
||||||
}
|
|
||||||
|
|
||||||
return _localIpAddresses;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<IPAddress> GetLocalIpAddressesInternal()
|
|
||||||
{
|
|
||||||
var list = GetIPsDefault().ToList();
|
|
||||||
|
|
||||||
if (list.Count == 0)
|
|
||||||
{
|
|
||||||
list = GetLocalIpAddressesFallback().GetAwaiter().GetResult().ToList();
|
|
||||||
}
|
|
||||||
|
|
||||||
var listClone = new List<IPAddress>();
|
|
||||||
|
|
||||||
var subnets = LocalSubnetsFn();
|
|
||||||
|
|
||||||
foreach (var i in list)
|
|
||||||
{
|
|
||||||
if (i.IsIPv6LinkLocal || i.ToString().StartsWith("169.254.", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Array.IndexOf(subnets, $"[{i}]") == -1)
|
|
||||||
{
|
|
||||||
listClone.Add(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return listClone
|
|
||||||
.OrderBy(i => i.AddressFamily == AddressFamily.InterNetwork ? 0 : 1)
|
|
||||||
// .ThenBy(i => listClone.IndexOf(i))
|
|
||||||
.GroupBy(i => i.ToString())
|
|
||||||
.Select(x => x.First())
|
|
||||||
.ToList();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public bool IsInPrivateAddressSpace(string endpoint)
|
|
||||||
{
|
|
||||||
return IsInPrivateAddressSpace(endpoint, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Checks if the address in endpoint is an RFC1918, RFC1122, or RFC3927 address
|
|
||||||
private bool IsInPrivateAddressSpace(string endpoint, bool checkSubnets)
|
|
||||||
{
|
|
||||||
if (string.Equals(endpoint, "::1", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// IPV6
|
|
||||||
if (endpoint.Split('.').Length > 4)
|
|
||||||
{
|
|
||||||
// Handle ipv4 mapped to ipv6
|
|
||||||
var originalEndpoint = endpoint;
|
|
||||||
endpoint = endpoint.Replace("::ffff:", string.Empty, StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
if (string.Equals(endpoint, originalEndpoint, StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Private address space:
|
|
||||||
|
|
||||||
if (string.Equals(endpoint, "localhost", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!IPAddress.TryParse(endpoint, out var ipAddress))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetAddressBytes
|
|
||||||
Span<byte> octet = stackalloc byte[ipAddress.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
|
|
||||||
ipAddress.TryWriteBytes(octet, out _);
|
|
||||||
|
|
||||||
if ((octet[0] == 10) ||
|
|
||||||
(octet[0] == 172 && (octet[1] >= 16 && octet[1] <= 31)) || // RFC1918
|
|
||||||
(octet[0] == 192 && octet[1] == 168) || // RFC1918
|
|
||||||
(octet[0] == 127) || // RFC1122
|
|
||||||
(octet[0] == 169 && octet[1] == 254)) // RFC3927
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (checkSubnets && IsInPrivateAddressSpaceAndLocalSubnet(endpoint))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint)
|
|
||||||
{
|
|
||||||
if (endpoint.StartsWith("10.", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
var endpointFirstPart = endpoint.Split('.')[0];
|
|
||||||
|
|
||||||
var subnets = GetSubnets(endpointFirstPart);
|
|
||||||
|
|
||||||
foreach (var subnet_Match in subnets)
|
|
||||||
{
|
|
||||||
// logger.LogDebug("subnet_Match:" + subnet_Match);
|
|
||||||
|
|
||||||
if (endpoint.StartsWith(subnet_Match + ".", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gives a list of possible subnets from the system whose interface ip starts with endpointFirstPart
|
|
||||||
private List<string> GetSubnets(string endpointFirstPart)
|
|
||||||
{
|
|
||||||
lock (_subnetLookupLock)
|
|
||||||
{
|
|
||||||
if (_subnetLookup.TryGetValue(endpointFirstPart, out var subnets))
|
|
||||||
{
|
|
||||||
return subnets;
|
|
||||||
}
|
|
||||||
|
|
||||||
subnets = new List<string>();
|
|
||||||
|
|
||||||
foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
|
|
||||||
{
|
|
||||||
foreach (var unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
|
|
||||||
{
|
|
||||||
if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork && endpointFirstPart == unicastIPAddressInformation.Address.ToString().Split('.')[0])
|
|
||||||
{
|
|
||||||
int subnet_Test = 0;
|
|
||||||
foreach (string part in unicastIPAddressInformation.IPv4Mask.ToString().Split('.'))
|
|
||||||
{
|
|
||||||
if (part.Equals("0", StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
subnet_Test++;
|
|
||||||
}
|
|
||||||
|
|
||||||
var subnet_Match = string.Join(".", unicastIPAddressInformation.Address.ToString().Split('.').Take(subnet_Test).ToArray());
|
|
||||||
|
|
||||||
// TODO: Is this check necessary?
|
|
||||||
if (adapter.OperationalStatus == OperationalStatus.Up)
|
|
||||||
{
|
|
||||||
subnets.Add(subnet_Match);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_subnetLookup[endpointFirstPart] = subnets;
|
|
||||||
|
|
||||||
return subnets;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public bool IsInLocalNetwork(string endpoint)
|
|
||||||
{
|
|
||||||
return IsInLocalNetworkInternal(endpoint, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public bool IsAddressInSubnets(string addressString, string[] subnets)
|
|
||||||
{
|
|
||||||
return IsAddressInSubnets(IPAddress.Parse(addressString), addressString, subnets);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC)
|
|
||||||
{
|
|
||||||
// GetAddressBytes
|
|
||||||
Span<byte> octet = stackalloc byte[address.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
|
|
||||||
address.TryWriteBytes(octet, out _);
|
|
||||||
|
|
||||||
if ((octet[0] == 127) || // RFC1122
|
|
||||||
(octet[0] == 169 && octet[1] == 254)) // RFC3927
|
|
||||||
{
|
|
||||||
// don't use on loopback or 169 interfaces
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
string addressString = address.ToString();
|
|
||||||
string excludeAddress = "[" + addressString + "]";
|
|
||||||
var subnets = LocalSubnetsFn();
|
|
||||||
|
|
||||||
// Include any address if LAN subnets aren't specified
|
|
||||||
if (subnets.Length == 0)
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Exclude any addresses if they appear in the LAN list in [ ]
|
|
||||||
if (Array.IndexOf(subnets, excludeAddress) != -1)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return IsAddressInSubnets(address, addressString, subnets);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Checks if the give address falls within the ranges given in [subnets]. The addresses in subnets can be hosts or subnets in the CIDR format.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="address">IPAddress version of the address.</param>
|
|
||||||
/// <param name="addressString">The address to check.</param>
|
|
||||||
/// <param name="subnets">If true, check against addresses in the LAN settings which have [] arroud and return true if it matches the address give in address.</param>
|
|
||||||
/// <returns><c>false</c>if the address isn't in the subnets, <c>true</c> otherwise.</returns>
|
|
||||||
private static bool IsAddressInSubnets(IPAddress address, string addressString, string[] subnets)
|
|
||||||
{
|
|
||||||
foreach (var subnet in subnets)
|
|
||||||
{
|
|
||||||
var normalizedSubnet = subnet.Trim();
|
|
||||||
// Is the subnet a host address and does it match the address being passes?
|
|
||||||
if (string.Equals(normalizedSubnet, addressString, StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse CIDR subnets and see if address falls within it.
|
|
||||||
if (normalizedSubnet.Contains('/', StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var ipNetwork = IPNetwork.Parse(normalizedSubnet);
|
|
||||||
if (ipNetwork.Contains(address))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
// Ignoring - invalid subnet passed encountered.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool IsInLocalNetworkInternal(string endpoint, bool resolveHost)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrEmpty(endpoint))
|
|
||||||
{
|
|
||||||
throw new ArgumentNullException(nameof(endpoint));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (IPAddress.TryParse(endpoint, out var address))
|
|
||||||
{
|
|
||||||
var addressString = address.ToString();
|
|
||||||
|
|
||||||
var localSubnetsFn = LocalSubnetsFn;
|
|
||||||
if (localSubnetsFn != null)
|
|
||||||
{
|
|
||||||
var localSubnets = localSubnetsFn();
|
|
||||||
foreach (var subnet in localSubnets)
|
|
||||||
{
|
|
||||||
// Only validate if there's at least one valid entry.
|
|
||||||
if (!string.IsNullOrWhiteSpace(subnet))
|
|
||||||
{
|
|
||||||
return IsAddressInSubnets(address, addressString, localSubnets) || IsInPrivateAddressSpace(addressString, false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
int lengthMatch = 100;
|
|
||||||
if (address.AddressFamily == AddressFamily.InterNetwork)
|
|
||||||
{
|
|
||||||
lengthMatch = 4;
|
|
||||||
if (IsInPrivateAddressSpace(addressString, true))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (address.AddressFamily == AddressFamily.InterNetworkV6)
|
|
||||||
{
|
|
||||||
lengthMatch = 9;
|
|
||||||
if (IsInPrivateAddressSpace(endpoint, true))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Should be even be doing this with ipv6?
|
|
||||||
if (addressString.Length >= lengthMatch)
|
|
||||||
{
|
|
||||||
var prefix = addressString.Substring(0, lengthMatch);
|
|
||||||
|
|
||||||
if (GetLocalIpAddresses().Any(i => i.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (resolveHost)
|
|
||||||
{
|
|
||||||
if (Uri.TryCreate(endpoint, UriKind.RelativeOrAbsolute, out var uri))
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var host = uri.DnsSafeHost;
|
|
||||||
_logger.LogDebug("Resolving host {0}", host);
|
|
||||||
|
|
||||||
address = GetIpAddresses(host).GetAwaiter().GetResult().FirstOrDefault();
|
|
||||||
|
|
||||||
if (address != null)
|
|
||||||
{
|
|
||||||
_logger.LogDebug("{0} resolved to {1}", host, address);
|
|
||||||
|
|
||||||
return IsInLocalNetworkInternal(address.ToString(), false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (InvalidOperationException)
|
|
||||||
{
|
|
||||||
// Can happen with reverse proxy or IIS url rewriting?
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "Error resolving hostname");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Task<IPAddress[]> GetIpAddresses(string hostName)
|
|
||||||
{
|
|
||||||
return Dns.GetHostAddressesAsync(hostName);
|
|
||||||
}
|
|
||||||
|
|
||||||
private IEnumerable<IPAddress> GetIPsDefault()
|
|
||||||
{
|
|
||||||
IEnumerable<NetworkInterface> interfaces;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
interfaces = NetworkInterface.GetAllNetworkInterfaces()
|
|
||||||
.Where(x => x.OperationalStatus == OperationalStatus.Up
|
|
||||||
|| x.OperationalStatus == OperationalStatus.Unknown);
|
|
||||||
}
|
|
||||||
catch (NetworkInformationException ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "Error in GetAllNetworkInterfaces");
|
|
||||||
return Enumerable.Empty<IPAddress>();
|
|
||||||
}
|
|
||||||
|
|
||||||
return interfaces.SelectMany(network =>
|
|
||||||
{
|
|
||||||
var ipProperties = network.GetIPProperties();
|
|
||||||
|
|
||||||
// Exclude any addresses if they appear in the LAN list in [ ]
|
|
||||||
|
|
||||||
return ipProperties.UnicastAddresses
|
|
||||||
.Select(i => i.Address)
|
|
||||||
.Where(i => i.AddressFamily == AddressFamily.InterNetwork || i.AddressFamily == AddressFamily.InterNetworkV6);
|
|
||||||
}).GroupBy(i => i.ToString())
|
|
||||||
.Select(x => x.First());
|
|
||||||
}
|
|
||||||
|
|
||||||
private static async Task<IEnumerable<IPAddress>> GetLocalIpAddressesFallback()
|
|
||||||
{
|
|
||||||
var host = await Dns.GetHostEntryAsync(Dns.GetHostName()).ConfigureAwait(false);
|
|
||||||
|
|
||||||
// Reverse them because the last one is usually the correct one
|
|
||||||
// It's not fool-proof so ultimately the consumer will have to examine them and decide
|
|
||||||
return host.AddressList
|
|
||||||
.Where(i => i.AddressFamily == AddressFamily.InterNetwork || i.AddressFamily == AddressFamily.InterNetworkV6)
|
|
||||||
.Reverse();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets a random port number that is currently available.
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>System.Int32.</returns>
|
|
||||||
public int GetRandomUnusedTcpPort()
|
|
||||||
{
|
|
||||||
var listener = new TcpListener(IPAddress.Any, 0);
|
|
||||||
listener.Start();
|
|
||||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
|
||||||
listener.Stop();
|
|
||||||
return port;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public int GetRandomUnusedUdpPort()
|
|
||||||
{
|
|
||||||
var localEndPoint = new IPEndPoint(IPAddress.Any, 0);
|
|
||||||
using (var udpClient = new UdpClient(localEndPoint))
|
|
||||||
{
|
|
||||||
return ((IPEndPoint)udpClient.Client.LocalEndPoint).Port;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public List<PhysicalAddress> GetMacAddresses()
|
|
||||||
{
|
|
||||||
return _macAddresses ??= GetMacAddressesInternal().ToList();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static IEnumerable<PhysicalAddress> GetMacAddressesInternal()
|
|
||||||
=> NetworkInterface.GetAllNetworkInterfaces()
|
|
||||||
.Where(i => i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
|
|
||||||
.Select(x => x.GetPhysicalAddress())
|
|
||||||
.Where(x => !x.Equals(PhysicalAddress.None));
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask)
|
|
||||||
{
|
|
||||||
IPAddress network1 = GetNetworkAddress(address1, subnetMask);
|
|
||||||
IPAddress network2 = GetNetworkAddress(address2, subnetMask);
|
|
||||||
return network1.Equals(network2);
|
|
||||||
}
|
|
||||||
|
|
||||||
private IPAddress GetNetworkAddress(IPAddress address, IPAddress subnetMask)
|
|
||||||
{
|
|
||||||
int size = address.AddressFamily == AddressFamily.InterNetwork ? 4 : 16;
|
|
||||||
|
|
||||||
// GetAddressBytes
|
|
||||||
Span<byte> ipAddressBytes = stackalloc byte[size];
|
|
||||||
address.TryWriteBytes(ipAddressBytes, out _);
|
|
||||||
|
|
||||||
// GetAddressBytes
|
|
||||||
Span<byte> subnetMaskBytes = stackalloc byte[size];
|
|
||||||
subnetMask.TryWriteBytes(subnetMaskBytes, out _);
|
|
||||||
|
|
||||||
if (ipAddressBytes.Length != subnetMaskBytes.Length)
|
|
||||||
{
|
|
||||||
throw new ArgumentException("Lengths of IP address and subnet mask do not match.");
|
|
||||||
}
|
|
||||||
|
|
||||||
byte[] broadcastAddress = new byte[ipAddressBytes.Length];
|
|
||||||
for (int i = 0; i < broadcastAddress.Length; i++)
|
|
||||||
{
|
|
||||||
broadcastAddress[i] = (byte)(ipAddressBytes[i] & subnetMaskBytes[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new IPAddress(broadcastAddress);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <inheritdoc/>
|
|
||||||
public IPAddress GetLocalIpSubnetMask(IPAddress address)
|
|
||||||
{
|
|
||||||
NetworkInterface[] interfaces;
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var validStatuses = new[] { OperationalStatus.Up, OperationalStatus.Unknown };
|
|
||||||
|
|
||||||
interfaces = NetworkInterface.GetAllNetworkInterfaces()
|
|
||||||
.Where(i => validStatuses.Contains(i.OperationalStatus))
|
|
||||||
.ToArray();
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "Error in GetAllNetworkInterfaces");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (NetworkInterface ni in interfaces)
|
|
||||||
{
|
|
||||||
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
|
|
||||||
{
|
|
||||||
if (ip.Address.Equals(address) && ip.IPv4Mask != null)
|
|
||||||
{
|
|
||||||
return ip.IPv4Mask;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -0,0 +1,71 @@
|
|||||||
|
using System;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace Jellyfin.Api.Helpers
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// A static class for copying matching properties from one object to another.
|
||||||
|
/// TODO: remove at the point when a fixed migration path has been decided upon.
|
||||||
|
/// </summary>
|
||||||
|
public static class ClassMigrationHelper
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Extension for 'Object' that copies the properties to a destination object.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source">The source.</param>
|
||||||
|
/// <param name="destination">The destination.</param>
|
||||||
|
public static void CopyProperties(this object source, object destination)
|
||||||
|
{
|
||||||
|
// If any this null throw an exception.
|
||||||
|
if (source == null || destination == null)
|
||||||
|
{
|
||||||
|
throw new Exception("Source or/and Destination Objects are null");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Getting the Types of the objects.
|
||||||
|
Type typeDest = destination.GetType();
|
||||||
|
Type typeSrc = source.GetType();
|
||||||
|
|
||||||
|
// Iterate the Properties of the source instance and populate them from their destination counterparts.
|
||||||
|
PropertyInfo[] srcProps = typeSrc.GetProperties();
|
||||||
|
foreach (PropertyInfo srcProp in srcProps)
|
||||||
|
{
|
||||||
|
if (!srcProp.CanRead)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var targetProperty = typeDest.GetProperty(srcProp.Name);
|
||||||
|
if (targetProperty == null)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!targetProperty.CanWrite)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var obj = targetProperty.GetSetMethod(true);
|
||||||
|
if (obj != null && obj.IsPrivate)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var target = targetProperty.GetSetMethod();
|
||||||
|
if (target != null && (target.Attributes & MethodAttributes.Static) != 0)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Passed all tests, lets set the value.
|
||||||
|
targetProperty.SetValue(destination, srcProp.GetValue(source, null), null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,234 +0,0 @@
|
|||||||
#nullable enable
|
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Collections.ObjectModel;
|
|
||||||
using System.Net;
|
|
||||||
using System.Net.NetworkInformation;
|
|
||||||
using Jellyfin.Networking.Configuration;
|
|
||||||
using MediaBrowser.Common.Net;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
|
|
||||||
namespace Jellyfin.Networking.Manager
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Interface for the NetworkManager class.
|
|
||||||
/// </summary>
|
|
||||||
public interface INetworkManager
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Event triggered on network changes.
|
|
||||||
/// </summary>
|
|
||||||
event EventHandler NetworkChanged;
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets the published server urls list.
|
|
||||||
/// </summary>
|
|
||||||
Dictionary<IPNetAddress, string> PublishedServerUrls { get; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
|
|
||||||
/// </summary>
|
|
||||||
bool TrustAllIP6Interfaces { get; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets the remote address filter.
|
|
||||||
/// </summary>
|
|
||||||
Collection<IPObject> RemoteAddressFilter { get; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets a value indicating whether iP6 is enabled.
|
|
||||||
/// </summary>
|
|
||||||
bool IsIP6Enabled { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets or sets a value indicating whether iP4 is enabled.
|
|
||||||
/// </summary>
|
|
||||||
bool IsIP4Enabled { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Calculates the list of interfaces to use for Kestrel.
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>A Collection{IPObject} object containing all the interfaces to bind.
|
|
||||||
/// If all the interfaces are specified, and none are excluded, it returns zero items
|
|
||||||
/// to represent any address.</returns>
|
|
||||||
/// <param name="individualInterfaces">When false, return <see cref="IPAddress.Any"/> or <see cref="IPAddress.IPv6Any"/> for all interfaces.</param>
|
|
||||||
Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns a collection containing the loopback interfaces.
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>Collection{IPObject}.</returns>
|
|
||||||
Collection<IPObject> GetLoopbacks();
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
|
|
||||||
/// If no bind addresses are specified, an internal interface address is selected.
|
|
||||||
/// The priority of selection is as follows:-
|
|
||||||
///
|
|
||||||
/// The value contained in the startup parameter --published-server-url.
|
|
||||||
///
|
|
||||||
/// If the user specified custom subnet overrides, the correct subnet for the source address.
|
|
||||||
///
|
|
||||||
/// If the user specified bind interfaces to use:-
|
|
||||||
/// The bind interface that contains the source subnet.
|
|
||||||
/// The first bind interface specified that suits best first the source's endpoint. eg. external or internal.
|
|
||||||
///
|
|
||||||
/// 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.
|
|
||||||
///
|
|
||||||
/// 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.
|
|
||||||
///
|
|
||||||
/// If no interfaces meet any of these criteria, then a loopback address is returned.
|
|
||||||
///
|
|
||||||
/// Interface that have been specifically excluded from binding are not used in any of the calculations.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="source">Source of the request.</param>
|
|
||||||
/// <param name="port">Optional port returned, if it's part of an override.</param>
|
|
||||||
/// <returns>IP Address to use, or loopback address if all else fails.</returns>
|
|
||||||
string GetBindInterface(IPObject source, out int? port);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
|
|
||||||
/// If no bind addresses are specified, an internal interface address is selected.
|
|
||||||
/// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="source">Source of the request.</param>
|
|
||||||
/// <param name="port">Optional port returned, if it's part of an override.</param>
|
|
||||||
/// <returns>IP Address to use, or loopback address if all else fails.</returns>
|
|
||||||
string GetBindInterface(HttpRequest source, out int? port);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
|
|
||||||
/// If no bind addresses are specified, an internal interface address is selected.
|
|
||||||
/// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="source">IP address of the request.</param>
|
|
||||||
/// <param name="port">Optional port returned, if it's part of an override.</param>
|
|
||||||
/// <returns>IP Address to use, or loopback address if all else fails.</returns>
|
|
||||||
string GetBindInterface(IPAddress source, out int? port);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
|
|
||||||
/// If no bind addresses are specified, an internal interface address is selected.
|
|
||||||
/// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="source">Source of the request.</param>
|
|
||||||
/// <param name="port">Optional port returned, if it's part of an override.</param>
|
|
||||||
/// <returns>IP Address to use, or loopback address if all else fails.</returns>
|
|
||||||
string GetBindInterface(string source, out int? port);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="address">IP address to check.</param>
|
|
||||||
/// <returns>True if it is.</returns>
|
|
||||||
bool IsExcludedInterface(IPAddress address);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Get a list of all the MAC addresses associated with active interfaces.
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>List of MAC addresses.</returns>
|
|
||||||
IReadOnlyCollection<PhysicalAddress> GetMacAddresses();
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Checks to see if the IP Address provided matches an interface that has a gateway.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
|
|
||||||
/// <returns>Result of the check.</returns>
|
|
||||||
bool IsGatewayInterface(IPObject? addressObj);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Checks to see if the IP Address provided matches an interface that has a gateway.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
|
|
||||||
/// <returns>Result of the check.</returns>
|
|
||||||
bool IsGatewayInterface(IPAddress? addressObj);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns true if the address is a private address.
|
|
||||||
/// The config option TrustIP6Interfaces overrides this functions behaviour.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="address">Address to check.</param>
|
|
||||||
/// <returns>True or False.</returns>
|
|
||||||
bool IsPrivateAddressRange(IPObject address);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns true if the address is part of the user defined LAN.
|
|
||||||
/// The config option TrustIP6Interfaces overrides this functions behaviour.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="address">IP to check.</param>
|
|
||||||
/// <returns>True if endpoint is within the LAN range.</returns>
|
|
||||||
bool IsInLocalNetwork(string address);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns true if the address is part of the user defined LAN.
|
|
||||||
/// The config option TrustIP6Interfaces overrides this functions behaviour.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="address">IP to check.</param>
|
|
||||||
/// <returns>True if endpoint is within the LAN range.</returns>
|
|
||||||
bool IsInLocalNetwork(IPObject address);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns true if the address is part of the user defined LAN.
|
|
||||||
/// The config option TrustIP6Interfaces overrides this functions behaviour.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="address">IP to check.</param>
|
|
||||||
/// <returns>True if endpoint is within the LAN range.</returns>
|
|
||||||
bool IsInLocalNetwork(IPAddress address);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Attempts to convert the token to an IP address, permitting for interface descriptions and indexes.
|
|
||||||
/// eg. "eth1", or "TP-LINK Wireless USB Adapter".
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="token">Token to parse.</param>
|
|
||||||
/// <param name="result">Resultant object's ip addresses, if successful.</param>
|
|
||||||
/// <returns>Success of the operation.</returns>
|
|
||||||
bool TryParseInterface(string token, out Collection<IPObject>? result);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Parses an array of strings into a Collection{IPObject}.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="values">Values to parse.</param>
|
|
||||||
/// <param name="bracketed">When true, only include values in []. When false, ignore bracketed values.</param>
|
|
||||||
/// <returns>IPCollection object containing the value strings.</returns>
|
|
||||||
Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns all the internal Bind interface addresses.
|
|
||||||
/// </summary>
|
|
||||||
/// <returns>An internal list of interfaces addresses.</returns>
|
|
||||||
Collection<IPObject> GetInternalBindAddresses();
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Checks to see if an IP address is still a valid interface address.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="address">IP address to check.</param>
|
|
||||||
/// <returns>True if it is.</returns>
|
|
||||||
bool IsValidInterfaceAddress(IPAddress address);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns true if the IP address is in the excluded list.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="ip">IP to check.</param>
|
|
||||||
/// <returns>True if excluded.</returns>
|
|
||||||
bool IsExcluded(IPAddress ip);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Returns true if the IP address is in the excluded list.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="ip">IP to check.</param>
|
|
||||||
/// <returns>True if excluded.</returns>
|
|
||||||
bool IsExcluded(EndPoint ip);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Gets the filtered LAN ip addresses.
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="filter">Optional filter for the list.</param>
|
|
||||||
/// <returns>Returns a filtered list of LAN addresses.</returns>
|
|
||||||
Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,97 +1,233 @@
|
|||||||
#pragma warning disable CS1591
|
#nullable enable
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Collections.ObjectModel;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Net.NetworkInformation;
|
using System.Net.NetworkInformation;
|
||||||
|
using MediaBrowser.Common.Net;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
|
||||||
namespace MediaBrowser.Common.Net
|
namespace MediaBrowser.Common.Net
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Interface for the NetworkManager class.
|
||||||
|
/// </summary>
|
||||||
public interface INetworkManager
|
public interface INetworkManager
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Event triggered on network changes.
|
||||||
|
/// </summary>
|
||||||
event EventHandler NetworkChanged;
|
event EventHandler NetworkChanged;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets a function to return the list of user defined LAN addresses.
|
/// Gets the published server urls list.
|
||||||
|
/// </summary>
|
||||||
|
Dictionary<IPNetAddress, string> PublishedServerUrls { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
|
||||||
|
/// </summary>
|
||||||
|
bool TrustAllIP6Interfaces { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the remote address filter.
|
||||||
|
/// </summary>
|
||||||
|
Collection<IPObject> RemoteAddressFilter { get; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether iP6 is enabled.
|
||||||
|
/// </summary>
|
||||||
|
bool IsIP6Enabled { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets or sets a value indicating whether iP4 is enabled.
|
||||||
|
/// </summary>
|
||||||
|
bool IsIP4Enabled { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Calculates the list of interfaces to use for Kestrel.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A Collection{IPObject} object containing all the interfaces to bind.
|
||||||
|
/// If all the interfaces are specified, and none are excluded, it returns zero items
|
||||||
|
/// to represent any address.</returns>
|
||||||
|
/// <param name="individualInterfaces">When false, return <see cref="IPAddress.Any"/> or <see cref="IPAddress.IPv6Any"/> for all interfaces.</param>
|
||||||
|
Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns a collection containing the loopback interfaces.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>Collection{IPObject}.</returns>
|
||||||
|
Collection<IPObject> GetLoopbacks();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
|
||||||
|
/// If no bind addresses are specified, an internal interface address is selected.
|
||||||
|
/// The priority of selection is as follows:-
|
||||||
|
///
|
||||||
|
/// The value contained in the startup parameter --published-server-url.
|
||||||
|
///
|
||||||
|
/// If the user specified custom subnet overrides, the correct subnet for the source address.
|
||||||
|
///
|
||||||
|
/// If the user specified bind interfaces to use:-
|
||||||
|
/// The bind interface that contains the source subnet.
|
||||||
|
/// The first bind interface specified that suits best first the source's endpoint. eg. external or internal.
|
||||||
|
///
|
||||||
|
/// 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.
|
||||||
|
///
|
||||||
|
/// 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.
|
||||||
|
///
|
||||||
|
/// If no interfaces meet any of these criteria, then a loopback address is returned.
|
||||||
|
///
|
||||||
|
/// Interface that have been specifically excluded from binding are not used in any of the calculations.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source">Source of the request.</param>
|
||||||
|
/// <param name="port">Optional port returned, if it's part of an override.</param>
|
||||||
|
/// <returns>IP Address to use, or loopback address if all else fails.</returns>
|
||||||
|
string GetBindInterface(IPObject source, out int? port);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
|
||||||
|
/// If no bind addresses are specified, an internal interface address is selected.
|
||||||
|
/// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source">Source of the request.</param>
|
||||||
|
/// <param name="port">Optional port returned, if it's part of an override.</param>
|
||||||
|
/// <returns>IP Address to use, or loopback address if all else fails.</returns>
|
||||||
|
string GetBindInterface(HttpRequest source, out int? port);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
|
||||||
|
/// If no bind addresses are specified, an internal interface address is selected.
|
||||||
|
/// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source">IP address of the request.</param>
|
||||||
|
/// <param name="port">Optional port returned, if it's part of an override.</param>
|
||||||
|
/// <returns>IP Address to use, or loopback address if all else fails.</returns>
|
||||||
|
string GetBindInterface(IPAddress source, out int? port);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
|
||||||
|
/// If no bind addresses are specified, an internal interface address is selected.
|
||||||
|
/// (See <see cref="GetBindInterface(IPObject, out int?)"/>.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source">Source of the request.</param>
|
||||||
|
/// <param name="port">Optional port returned, if it's part of an override.</param>
|
||||||
|
/// <returns>IP Address to use, or loopback address if all else fails.</returns>
|
||||||
|
string GetBindInterface(string source, out int? port);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Checks to see if the ip address is specifically excluded in LocalNetworkAddresses.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="address">IP address to check.</param>
|
||||||
|
/// <returns>True if it is.</returns>
|
||||||
|
bool IsExcludedInterface(IPAddress address);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Get a list of all the MAC addresses associated with active interfaces.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>List of MAC addresses.</returns>
|
||||||
|
IReadOnlyCollection<PhysicalAddress> GetMacAddresses();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Checks to see if the IP Address provided matches an interface that has a gateway.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
|
||||||
|
/// <returns>Result of the check.</returns>
|
||||||
|
bool IsGatewayInterface(IPObject? addressObj);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Checks to see if the IP Address provided matches an interface that has a gateway.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
Func<string[]> LocalSubnetsFn { get; set; }
|
/// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
|
||||||
|
/// <returns>Result of the check.</returns>
|
||||||
|
bool IsGatewayInterface(IPAddress? addressObj);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets a random port TCP number that is currently available.
|
/// Returns true if the address is a private address.
|
||||||
|
/// The config option TrustIP6Interfaces overrides this functions behaviour.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>System.Int32.</returns>
|
/// <param name="address">Address to check.</param>
|
||||||
int GetRandomUnusedTcpPort();
|
/// <returns>True or False.</returns>
|
||||||
|
bool IsPrivateAddressRange(IPObject address);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets a random port UDP number that is currently available.
|
/// Returns true if the address is part of the user defined LAN.
|
||||||
|
/// The config option TrustIP6Interfaces overrides this functions behaviour.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>System.Int32.</returns>
|
/// <param name="address">IP to check.</param>
|
||||||
int GetRandomUnusedUdpPort();
|
/// <returns>True if endpoint is within the LAN range.</returns>
|
||||||
|
bool IsInLocalNetwork(string address);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns the MAC Address from first Network Card in Computer.
|
/// Returns true if the address is part of the user defined LAN.
|
||||||
|
/// The config option TrustIP6Interfaces overrides this functions behaviour.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>The MAC Address.</returns>
|
/// <param name="address">IP to check.</param>
|
||||||
List<PhysicalAddress> GetMacAddresses();
|
/// <returns>True if endpoint is within the LAN range.</returns>
|
||||||
|
bool IsInLocalNetwork(IPObject address);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Determines whether [is in private address space] [the specified endpoint].
|
/// Returns true if the address is part of the user defined LAN.
|
||||||
|
/// The config option TrustIP6Interfaces overrides this functions behaviour.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endpoint">The endpoint.</param>
|
/// <param name="address">IP to check.</param>
|
||||||
/// <returns><c>true</c> if [is in private address space] [the specified endpoint]; otherwise, <c>false</c>.</returns>
|
/// <returns>True if endpoint is within the LAN range.</returns>
|
||||||
bool IsInPrivateAddressSpace(string endpoint);
|
bool IsInLocalNetwork(IPAddress address);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Determines whether [is in private address space 10.x.x.x] [the specified endpoint] and exists in the subnets returned by GetSubnets().
|
/// Attempts to convert the token to an IP address, permitting for interface descriptions and indexes.
|
||||||
|
/// eg. "eth1", or "TP-LINK Wireless USB Adapter".
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endpoint">The endpoint.</param>
|
/// <param name="token">Token to parse.</param>
|
||||||
/// <returns><c>true</c> if [is in private address space 10.x.x.x] [the specified endpoint]; otherwise, <c>false</c>.</returns>
|
/// <param name="result">Resultant object's ip addresses, if successful.</param>
|
||||||
bool IsInPrivateAddressSpaceAndLocalSubnet(string endpoint);
|
/// <returns>Success of the operation.</returns>
|
||||||
|
bool TryParseInterface(string token, out Collection<IPObject>? result);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Determines whether [is in local network] [the specified endpoint].
|
/// Parses an array of strings into a Collection{IPObject}.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="endpoint">The endpoint.</param>
|
/// <param name="values">Values to parse.</param>
|
||||||
/// <returns><c>true</c> if [is in local network] [the specified endpoint]; otherwise, <c>false</c>.</returns>
|
/// <param name="bracketed">When true, only include values in []. When false, ignore bracketed values.</param>
|
||||||
bool IsInLocalNetwork(string endpoint);
|
/// <returns>IPCollection object containing the value strings.</returns>
|
||||||
|
Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Investigates an caches a list of interface addresses, excluding local link and LAN excluded addresses.
|
/// Returns all the internal Bind interface addresses.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>The list of ip addresses.</returns>
|
/// <returns>An internal list of interfaces addresses.</returns>
|
||||||
IPAddress[] GetLocalIpAddresses();
|
Collection<IPObject> GetInternalBindAddresses();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Checks if the given address falls within the ranges given in [subnets]. The addresses in subnets can be hosts or subnets in the CIDR format.
|
/// Checks to see if an IP address is still a valid interface address.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="addressString">The address to check.</param>
|
/// <param name="address">IP address to check.</param>
|
||||||
/// <param name="subnets">If true, check against addresses in the LAN settings surrounded by brackets ([]).</param>
|
/// <returns>True if it is.</returns>
|
||||||
/// <returns><c>true</c>if the address is in at least one of the given subnets, <c>false</c> otherwise.</returns>
|
bool IsValidInterfaceAddress(IPAddress address);
|
||||||
bool IsAddressInSubnets(string addressString, string[] subnets);
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns true if address is in the LAN list in the config file.
|
/// Returns true if the IP address is in the excluded list.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="address">The address to check.</param>
|
/// <param name="ip">IP to check.</param>
|
||||||
/// <param name="excludeInterfaces">If true, check against addresses in the LAN settings which have [] around and return true if it matches the address give in address.</param>
|
/// <returns>True if excluded.</returns>
|
||||||
/// <param name="excludeRFC">If true, returns false if address is in the 127.x.x.x or 169.128.x.x range.</param>
|
bool IsExcluded(IPAddress ip);
|
||||||
/// <returns><c>false</c>if the address isn't in the LAN list, <c>true</c> if the address has been defined as a LAN address.</returns>
|
|
||||||
bool IsAddressInSubnets(IPAddress address, bool excludeInterfaces, bool excludeRFC);
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Checks if address is in the LAN list in the config file.
|
/// Returns true if the IP address is in the excluded list.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="address1">Source address to check.</param>
|
/// <param name="ip">IP to check.</param>
|
||||||
/// <param name="address2">Destination address to check against.</param>
|
/// <returns>True if excluded.</returns>
|
||||||
/// <param name="subnetMask">Destination subnet to check against.</param>
|
bool IsExcluded(EndPoint ip);
|
||||||
/// <returns><c>true/false</c>depending on whether address1 is in the same subnet as IPAddress2 with subnetMask.</returns>
|
|
||||||
bool IsInSameSubnet(IPAddress address1, IPAddress address2, IPAddress subnetMask);
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Returns the subnet mask of an interface with the given address.
|
/// Gets the filtered LAN ip addresses.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="address">The address to check.</param>
|
/// <param name="filter">Optional filter for the list.</param>
|
||||||
/// <returns>Returns the subnet mask of an interface with the given address, or null if an interface match cannot be found.</returns>
|
/// <returns>Returns a filtered list of LAN addresses.</returns>
|
||||||
IPAddress GetLocalIpSubnetMask(IPAddress address);
|
Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,39 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!-- ProjectGuid is only included as a requirement for SonarQube analysis -->
|
||||||
|
<PropertyGroup>
|
||||||
|
<ProjectGuid>{42816EA8-4511-4CBF-A9C7-7791D5DDDAE6}</ProjectGuid>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net5.0</TargetFramework>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.0" />
|
||||||
|
<PackageReference Include="xunit" Version="2.4.1" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.1" />
|
||||||
|
<PackageReference Include="coverlet.collector" Version="1.3.0" />
|
||||||
|
<PackageReference Include="Moq" Version="4.14.5" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<!-- Code Analyzers-->
|
||||||
|
<ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||||
|
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8" PrivateAssets="All" />
|
||||||
|
<PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
|
||||||
|
<PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\..\Emby.Server.Implementations\Emby.Server.Implementations.csproj" />
|
||||||
|
<ProjectReference Include="..\..\..\MediaBrowser.Common\MediaBrowser.Common.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||||
|
<CodeAnalysisRuleSet>../../jellyfin-tests.ruleset</CodeAnalysisRuleSet>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||||
|
<DefineConstants>DEBUG</DefineConstants>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
@ -0,0 +1,517 @@
|
|||||||
|
using System;
|
||||||
|
using System.Net;
|
||||||
|
using Jellyfin.Networking.Configuration;
|
||||||
|
using Jellyfin.Networking.Manager;
|
||||||
|
using MediaBrowser.Common.Configuration;
|
||||||
|
using MediaBrowser.Common.Net;
|
||||||
|
using Moq;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
using Xunit;
|
||||||
|
using System.Collections.ObjectModel;
|
||||||
|
|
||||||
|
namespace Jellyfin.Networking.Tests
|
||||||
|
{
|
||||||
|
public class NetworkParseTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Tries to identify the string and return an object of that class.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="addr">String to parse.</param>
|
||||||
|
/// <param name="result">IPObject to return.</param>
|
||||||
|
/// <returns>True if the value parsed successfully.</returns>
|
||||||
|
private static bool TryParse(string addr, out IPObject result)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrEmpty(addr))
|
||||||
|
{
|
||||||
|
// Is it an IP address
|
||||||
|
if (IPNetAddress.TryParse(addr, out IPNetAddress nw))
|
||||||
|
{
|
||||||
|
result = nw;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IPHost.TryParse(addr, out IPHost h))
|
||||||
|
{
|
||||||
|
result = h;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result = IPNetAddress.None;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IConfigurationManager GetMockConfig(NetworkConfiguration conf)
|
||||||
|
{
|
||||||
|
var configManager = new Mock<IConfigurationManager>
|
||||||
|
{
|
||||||
|
CallBase = true
|
||||||
|
};
|
||||||
|
configManager.Setup(x => x.GetConfiguration(It.IsAny<string>())).Returns(conf);
|
||||||
|
return (IConfigurationManager)configManager.Object;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Checks the ability to ignore interfaces
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="interfaces">Mock network setup, in the format (IP address, interface index, interface name) : .... </param>
|
||||||
|
/// <param name="lan">LAN addresses.</param>
|
||||||
|
/// <param name="value">Bind addresses that are excluded.</param>
|
||||||
|
[Theory]
|
||||||
|
[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]")]
|
||||||
|
[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]")]
|
||||||
|
[InlineData("192.168.1.208/24,-16,vEthernet1:192.168.1.208/24,-16,vEthernet212;200.200.200.200/24,11,eth11", "192.168.1.0/24", "[192.168.1.208/24]")]
|
||||||
|
public void IgnoreVirtualInterfaces(string interfaces, string lan, string value)
|
||||||
|
{
|
||||||
|
var conf = new NetworkConfiguration()
|
||||||
|
{
|
||||||
|
EnableIPV6 = true,
|
||||||
|
EnableIPV4 = true,
|
||||||
|
LocalNetworkSubnets = lan?.Split(';') ?? throw new ArgumentNullException(nameof(lan))
|
||||||
|
};
|
||||||
|
|
||||||
|
NetworkManager.MockNetworkSettings = interfaces;
|
||||||
|
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
|
||||||
|
NetworkManager.MockNetworkSettings = string.Empty;
|
||||||
|
|
||||||
|
Assert.Equal(nm.GetInternalBindAddresses().AsString(), value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Check that the value given is in the network provided.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="network">Network address.</param>
|
||||||
|
/// <param name="value">Value to check.</param>
|
||||||
|
[Theory]
|
||||||
|
[InlineData("192.168.10.0/24, !192.168.10.60/32", "192.168.10.60")]
|
||||||
|
public void IsInNetwork(string network, string value)
|
||||||
|
{
|
||||||
|
if (network == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(network));
|
||||||
|
}
|
||||||
|
|
||||||
|
var conf = new NetworkConfiguration()
|
||||||
|
{
|
||||||
|
EnableIPV6 = true,
|
||||||
|
EnableIPV4 = true,
|
||||||
|
LocalNetworkSubnets = network.Split(',')
|
||||||
|
};
|
||||||
|
|
||||||
|
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
|
||||||
|
|
||||||
|
Assert.False(nm.IsInLocalNetwork(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Checks IP address formats.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="address"></param>
|
||||||
|
[Theory]
|
||||||
|
[InlineData("127.0.0.1")]
|
||||||
|
[InlineData("127.0.0.1:123")]
|
||||||
|
[InlineData("localhost")]
|
||||||
|
[InlineData("localhost:1345")]
|
||||||
|
[InlineData("www.google.co.uk")]
|
||||||
|
[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]:124")]
|
||||||
|
[InlineData("fe80::7add:12ff:febb:c67b%16")]
|
||||||
|
[InlineData("[fe80::7add:12ff:febb:c67b%16]:123")]
|
||||||
|
[InlineData("192.168.1.2/255.255.255.0")]
|
||||||
|
[InlineData("192.168.1.2/24")]
|
||||||
|
public void ValidIPStrings(string address)
|
||||||
|
{
|
||||||
|
Assert.True(TryParse(address, out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// All should be invalid address strings.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="address">Invalid address strings.</param>
|
||||||
|
[Theory]
|
||||||
|
[InlineData("256.128.0.0.0.1")]
|
||||||
|
[InlineData("127.0.0.1#")]
|
||||||
|
[InlineData("localhost!")]
|
||||||
|
[InlineData("fd23:184f:2029:0:3139:7386:67d7:d517:1231")]
|
||||||
|
public void InvalidAddressString(string address)
|
||||||
|
{
|
||||||
|
Assert.False(TryParse(address, out _));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Test collection parsing.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="settings">Collection to parse.</param>
|
||||||
|
/// <param name="result1">Included addresses from the collection.</param>
|
||||||
|
/// <param name="result2">Included IP4 addresses from the collection.</param>
|
||||||
|
/// <param name="result3">Excluded addresses from the collection.</param>
|
||||||
|
/// <param name="result4">Excluded IP4 addresses from the collection.</param>
|
||||||
|
/// <param name="result5">Network addresses of the collection.</param>
|
||||||
|
[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/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]")]
|
||||||
|
[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,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,fd23:184f:2029:0:3139:7386:67d7:d517/128]")]
|
||||||
|
public void TestCollections(string settings, string result1, string result2, string result3, string result4, string result5)
|
||||||
|
{
|
||||||
|
if (settings == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(settings));
|
||||||
|
}
|
||||||
|
|
||||||
|
var conf = new NetworkConfiguration()
|
||||||
|
{
|
||||||
|
EnableIPV6 = true,
|
||||||
|
EnableIPV4 = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
|
||||||
|
|
||||||
|
// Test included.
|
||||||
|
Collection<IPObject> nc = nm.CreateIPCollection(settings.Split(","), false);
|
||||||
|
Assert.Equal(nc.AsString(), result1);
|
||||||
|
|
||||||
|
// Test excluded.
|
||||||
|
nc = nm.CreateIPCollection(settings.Split(","), true);
|
||||||
|
Assert.Equal(nc.AsString(), result3);
|
||||||
|
|
||||||
|
conf.EnableIPV6 = false;
|
||||||
|
nm.UpdateSettings(conf);
|
||||||
|
|
||||||
|
// Test IP4 included.
|
||||||
|
nc = nm.CreateIPCollection(settings.Split(","), false);
|
||||||
|
Assert.Equal(nc.AsString(), result2);
|
||||||
|
|
||||||
|
// Test IP4 excluded.
|
||||||
|
nc = nm.CreateIPCollection(settings.Split(","), true);
|
||||||
|
Assert.Equal(nc.AsString(), result4);
|
||||||
|
|
||||||
|
conf.EnableIPV6 = true;
|
||||||
|
nm.UpdateSettings(conf);
|
||||||
|
|
||||||
|
// Test network addresses of collection.
|
||||||
|
nc = nm.CreateIPCollection(settings.Split(","), false);
|
||||||
|
nc = nc.AsNetworks();
|
||||||
|
Assert.Equal(nc.AsString(), result5);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Union two collections.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="settings">Source.</param>
|
||||||
|
/// <param name="compare">Destination.</param>
|
||||||
|
/// <param name="result">Result.</param>
|
||||||
|
[Theory]
|
||||||
|
[InlineData("127.0.0.1", "fd23:184f:2029:0:3139:7386:67d7:d517/64,fd23:184f:2029:0:c0f0:8a8a:7605:fffa/128,fe80::3139:7386:67d7:d517%16/64,192.168.1.208/24,::1/128,127.0.0.1/8", "[127.0.0.1/32]")]
|
||||||
|
[InlineData("127.0.0.1", "127.0.0.1/8", "[127.0.0.1/32]")]
|
||||||
|
public void UnionCheck(string settings, string compare, string result)
|
||||||
|
{
|
||||||
|
if (settings == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(settings));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (compare == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(compare));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(result));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
var conf = new NetworkConfiguration()
|
||||||
|
{
|
||||||
|
EnableIPV6 = true,
|
||||||
|
EnableIPV4 = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
|
||||||
|
|
||||||
|
Collection<IPObject> nc1 = nm.CreateIPCollection(settings.Split(","), false);
|
||||||
|
Collection<IPObject> nc2 = nm.CreateIPCollection(compare.Split(","), false);
|
||||||
|
|
||||||
|
Assert.Equal(nc1.Union(nc2).AsString(), result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("192.168.5.85/24", "192.168.5.1")]
|
||||||
|
[InlineData("192.168.5.85/24", "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("127.0.0.1/8", "127.0.0.1")]
|
||||||
|
public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress)
|
||||||
|
{
|
||||||
|
var ipAddressObj = IPNetAddress.Parse(netMask);
|
||||||
|
Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("192.168.5.85/24", "192.168.4.254")]
|
||||||
|
[InlineData("192.168.5.85/24", "191.168.5.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)
|
||||||
|
{
|
||||||
|
var ipAddressObj = IPNetAddress.Parse(netMask);
|
||||||
|
Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[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)
|
||||||
|
{
|
||||||
|
var ipAddressObj = IPNetAddress.Parse(netMask);
|
||||||
|
Assert.True(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFFF")]
|
||||||
|
[InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0000:0000:0000:0000")]
|
||||||
|
[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)
|
||||||
|
{
|
||||||
|
var ipAddressObj = IPNetAddress.Parse(netMask);
|
||||||
|
Assert.False(ipAddressObj.Contains(IPAddress.Parse(ipAddress)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("10.0.0.0/255.0.0.0", "10.10.10.1/32")]
|
||||||
|
[InlineData("10.0.0.0/8", "10.10.10.1/32")]
|
||||||
|
[InlineData("10.0.0.0/255.0.0.0", "10.10.10.1")]
|
||||||
|
|
||||||
|
[InlineData("10.10.0.0/255.255.0.0", "10.10.10.1/32")]
|
||||||
|
[InlineData("10.10.0.0/16", "10.10.10.1/32")]
|
||||||
|
[InlineData("10.10.0.0/255.255.0.0", "10.10.10.1")]
|
||||||
|
|
||||||
|
[InlineData("10.10.10.0/255.255.255.0", "10.10.10.1/32")]
|
||||||
|
[InlineData("10.10.10.0/24", "10.10.10.1/32")]
|
||||||
|
[InlineData("10.10.10.0/255.255.255.0", "10.10.10.1")]
|
||||||
|
|
||||||
|
public void TestSubnetContains(string network, string ip)
|
||||||
|
{
|
||||||
|
Assert.True(TryParse(network, out IPObject? networkObj));
|
||||||
|
Assert.True(TryParse(ip, out IPObject? ipObj));
|
||||||
|
Assert.True(networkObj.Contains(ipObj));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24", "172.168.1.2/24")]
|
||||||
|
[InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "172.168.1.2/24, 10.10.10.1", "172.168.1.2/24,10.10.10.1/24")]
|
||||||
|
[InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/255.255.255.0, 10.10.10.1", "192.168.1.2/24,10.10.10.1/24")]
|
||||||
|
[InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "192.168.1.2/24, 100.10.10.1", "192.168.1.2/24")]
|
||||||
|
[InlineData("192.168.1.2/24,10.10.10.1/24,172.168.1.2/24", "194.168.1.2/24, 100.10.10.1", "")]
|
||||||
|
|
||||||
|
public void TestCollectionEquality(string source, string dest, string result)
|
||||||
|
{
|
||||||
|
if (source == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(source));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dest == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(dest));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(result));
|
||||||
|
}
|
||||||
|
|
||||||
|
var conf = new NetworkConfiguration()
|
||||||
|
{
|
||||||
|
EnableIPV6 = true,
|
||||||
|
EnableIPV4 = true
|
||||||
|
};
|
||||||
|
|
||||||
|
using var nm = new NetworkManager(GetMockConfig(conf), new NullLogger<NetworkManager>());
|
||||||
|
|
||||||
|
// Test included, IP6.
|
||||||
|
Collection<IPObject> ncSource = nm.CreateIPCollection(source.Split(","));
|
||||||
|
Collection<IPObject> ncDest = nm.CreateIPCollection(dest.Split(","));
|
||||||
|
Collection<IPObject> ncResult = ncSource.Union(ncDest);
|
||||||
|
Collection<IPObject> resultCollection = nm.CreateIPCollection(result.Split(","));
|
||||||
|
Assert.True(ncResult.Compare(resultCollection));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("10.1.1.1/32", "10.1.1.1")]
|
||||||
|
[InlineData("192.168.1.254/32", "192.168.1.254/255.255.255.255")]
|
||||||
|
|
||||||
|
public void TestEquals(string source, string dest)
|
||||||
|
{
|
||||||
|
Assert.True(IPNetAddress.Parse(source).Equals(IPNetAddress.Parse(dest)));
|
||||||
|
Assert.True(IPNetAddress.Parse(dest).Equals(IPNetAddress.Parse(source)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
|
||||||
|
// Testing bind interfaces.
|
||||||
|
// On my system eth16 is internal, eth11 external (Windows defines the indexes).
|
||||||
|
//
|
||||||
|
// This test is to replicate how DNLA requests work throughout the system.
|
||||||
|
|
||||||
|
// User on internal network, we're bound internal and external - so result is internal.
|
||||||
|
[InlineData("192.168.1.1", "eth16,eth11", false, "eth16")]
|
||||||
|
// User on external network, we're bound internal and external - so result is external.
|
||||||
|
[InlineData("8.8.8.8", "eth16,eth11", false, "eth11")]
|
||||||
|
// User on internal network, we're bound internal only - so result is internal.
|
||||||
|
[InlineData("10.10.10.10", "eth16", false, "eth16")]
|
||||||
|
// User on internal network, no binding specified - so result is the 1st internal.
|
||||||
|
[InlineData("192.168.1.1", "", false, "eth16")]
|
||||||
|
// User on external network, internal binding only - so result is the 1st internal.
|
||||||
|
[InlineData("jellyfin.org", "eth16", false, "eth16")]
|
||||||
|
// User on external network, no binding - so result is the 1st external.
|
||||||
|
[InlineData("jellyfin.org", "", false, "eth11")]
|
||||||
|
// User assumed to be internal, no binding - so result is the 1st internal.
|
||||||
|
[InlineData("", "", false, "eth16")]
|
||||||
|
public void TestBindInterfaces(string source, string bindAddresses, bool ipv6enabled, string result)
|
||||||
|
{
|
||||||
|
if (source == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(source));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bindAddresses == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(bindAddresses));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(result));
|
||||||
|
}
|
||||||
|
|
||||||
|
var conf = new NetworkConfiguration()
|
||||||
|
{
|
||||||
|
LocalNetworkAddresses = bindAddresses.Split(','),
|
||||||
|
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>());
|
||||||
|
NetworkManager.MockNetworkSettings = string.Empty;
|
||||||
|
|
||||||
|
_ = nm.TryParseInterface(result, out Collection<IPObject>? resultObj);
|
||||||
|
|
||||||
|
if (resultObj != null)
|
||||||
|
{
|
||||||
|
result = ((IPNetAddress)resultObj[0]).ToString(true);
|
||||||
|
var intf = nm.GetBindInterface(source, out int? _);
|
||||||
|
|
||||||
|
Assert.Equal(intf, result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
|
||||||
|
// Testing bind interfaces. These are set for my system so won't work elsewhere.
|
||||||
|
// On my system eth16 is internal, eth11 external (Windows defines the indexes).
|
||||||
|
//
|
||||||
|
// This test is to replicate how subnet bound ServerPublisherUri work throughout the system.
|
||||||
|
|
||||||
|
// User on internal network, we're bound internal and external - so result is internal override.
|
||||||
|
[InlineData("192.168.1.1", "192.168.1.0/24", "eth16,eth11", false, "192.168.1.0/24=internal.jellyfin", "internal.jellyfin")]
|
||||||
|
|
||||||
|
// User on external network, we're bound internal and external - so result is override.
|
||||||
|
[InlineData("8.8.8.8", "192.168.1.0/24", "eth16,eth11", false, "0.0.0.0=http://helloworld.com", "http://helloworld.com")]
|
||||||
|
|
||||||
|
// User on internal network, we're bound internal only, but the address isn't in the LAN - so return the override.
|
||||||
|
[InlineData("10.10.10.10", "192.168.1.0/24", "eth16", false, "0.0.0.0=http://internalButNotDefinedAsLan.com", "http://internalButNotDefinedAsLan.com")]
|
||||||
|
|
||||||
|
// User on internal network, no binding specified - so result is the 1st internal.
|
||||||
|
[InlineData("192.168.1.1", "192.168.1.0/24", "", false, "0.0.0.0=http://helloworld.com", "eth16")]
|
||||||
|
|
||||||
|
// User on external network, internal binding only - so asumption 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 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")]
|
||||||
|
|
||||||
|
// User is internal, no binding - so result is the 1st internal, which is then overridden.
|
||||||
|
[InlineData("192.168.1.1", "192.168.1.0/24", "", false, "eth16=http://helloworld.com", "http://helloworld.com")]
|
||||||
|
|
||||||
|
public void TestBindInterfaceOverrides(string source, string lan, string bindAddresses, bool ipv6enabled, string publishedServers, string result)
|
||||||
|
{
|
||||||
|
if (lan == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(lan));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bindAddresses == null)
|
||||||
|
{
|
||||||
|
throw new ArgumentNullException(nameof(bindAddresses));
|
||||||
|
}
|
||||||
|
|
||||||
|
var conf = new NetworkConfiguration()
|
||||||
|
{
|
||||||
|
LocalNetworkSubnets = lan.Split(','),
|
||||||
|
LocalNetworkAddresses = bindAddresses.Split(','),
|
||||||
|
EnableIPV6 = ipv6enabled,
|
||||||
|
EnableIPV4 = true,
|
||||||
|
PublishedServerUriBySubnet = new string[] { publishedServers }
|
||||||
|
};
|
||||||
|
|
||||||
|
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>());
|
||||||
|
NetworkManager.MockNetworkSettings = string.Empty;
|
||||||
|
|
||||||
|
if (nm.TryParseInterface(result, out Collection<IPObject>? resultObj) && resultObj != null)
|
||||||
|
{
|
||||||
|
// Parse out IPAddresses so we can do a string comparison. (Ignore subnet masks).
|
||||||
|
result = ((IPNetAddress)resultObj[0]).ToString(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
var intf = nm.GetBindInterface(source, out int? _);
|
||||||
|
|
||||||
|
Assert.Equal(intf, result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in new issue