Updated PR1 code.

This commit is contained in:
Greenback 2020-11-16 19:37:38 +00:00
parent 979de240cb
commit 978aa38f3b
6 changed files with 188 additions and 200 deletions

View File

@ -11,12 +11,12 @@ namespace Jellyfin.Networking.Configuration
public class NetworkConfiguration public class NetworkConfiguration
{ {
/// <summary> /// <summary>
/// Gets the default http port. /// The default value for <see cref="HttpServerPortNumber"/>.
/// </summary> /// </summary>
public const int DefaultHttpPort = 8096; public const int DefaultHttpPort = 8096;
/// <summary> /// <summary>
/// Gets the default https port. /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsPortNumber"/>.
/// </summary> /// </summary>
public const int DefaultHttpsPort = 8920; public const int DefaultHttpsPort = 8920;
@ -94,124 +94,124 @@ namespace Jellyfin.Networking.Configuration
public int PublicPort { get; set; } = DefaultHttpPort; public int PublicPort { get; set; } = DefaultHttpPort;
/// <summary> /// <summary>
/// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.. /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.
/// </summary> /// </summary>
public bool UPnPCreateHttpPortMap { get; set; } public bool UPnPCreateHttpPortMap { get; set; }
/// <summary> /// <summary>
/// Gets or sets the UDPPortRange /// Gets or sets the UDPPortRange
/// Gets or sets client udp port range.. /// Gets or sets client udp port range.
/// </summary> /// </summary>
public string UDPPortRange { get; set; } = string.Empty; public string UDPPortRange { get; set; } = string.Empty;
/// <summary> /// <summary>
/// Gets or sets a value indicating whether gets or sets IPV6 capability.. /// Gets or sets a value indicating whether gets or sets IPV6 capability.
/// </summary> /// </summary>
public bool EnableIPV6 { get; set; } public bool EnableIPV6 { get; set; }
/// <summary> /// <summary>
/// Gets or sets a value indicating whether gets or sets IPV4 capability.. /// Gets or sets a value indicating whether gets or sets IPV4 capability.
/// </summary> /// </summary>
public bool EnableIPV4 { get; set; } = true; public bool EnableIPV4 { get; set; } = true;
/// <summary> /// <summary>
/// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log. /// 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 work.. /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work.
/// </summary> /// </summary>
public bool EnableSSDPTracing { get; set; } public bool EnableSSDPTracing { get; set; }
/// <summary> /// <summary>
/// Gets or sets the SSDPTracingFilter /// 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. /// 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.. /// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work.
/// </summary> /// </summary>
public string SSDPTracingFilter { get; set; } = string.Empty; public string SSDPTracingFilter { get; set; } = string.Empty;
/// <summary> /// <summary>
/// Gets or sets the number of times SSDP UDP messages are sent.. /// Gets or sets the number of times SSDP UDP messages are sent.
/// </summary> /// </summary>
public int UDPSendCount { get; set; } = 2; public int UDPSendCount { get; set; } = 2;
/// <summary> /// <summary>
/// Gets or sets the delay between each groups of SSDP messages (in ms).. /// Gets or sets the delay between each groups of SSDP messages (in ms).
/// </summary> /// </summary>
public int UDPSendDelay { get; set; } = 100; public int UDPSendDelay { get; set; } = 100;
/// <summary> /// <summary>
/// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding.. /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding.
/// </summary> /// </summary>
public bool IgnoreVirtualInterfaces { get; set; } = true; public bool IgnoreVirtualInterfaces { get; set; } = true;
/// <summary> /// <summary>
/// Gets or sets the VirtualInterfaceNames /// Gets or sets the VirtualInterfaceNames
/// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>.. /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. <seealso cref="IgnoreVirtualInterfaces"/>.
/// </summary> /// </summary>
public string VirtualInterfaceNames { get; set; } = "vEthernet*"; public string VirtualInterfaceNames { get; set; } = "vEthernet*";
/// <summary> /// <summary>
/// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor.. /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor.
/// </summary> /// </summary>
public int GatewayMonitorPeriod { get; set; } = 60; public int GatewayMonitorPeriod { get; set; } = 60;
/// <summary> /// <summary>
/// Gets a value indicating whether multi-socket binding is available.. /// Gets a value indicating whether multi-socket binding is available.
/// </summary> /// </summary>
public bool EnableMultiSocketBinding { get; } = true; public bool EnableMultiSocketBinding { get; } = true;
/// <summary> /// <summary>
/// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network. /// 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.. /// Depending on the address range implemented ULA ranges might not be used.
/// </summary> /// </summary>
public bool TrustAllIP6Interfaces { get; set; } public bool TrustAllIP6Interfaces { get; set; }
/// <summary> /// <summary>
/// Gets or sets the ports that HDHomerun uses.. /// Gets or sets the ports that HDHomerun uses.
/// </summary> /// </summary>
public string HDHomerunPortRange { get; set; } = string.Empty; public string HDHomerunPortRange { get; set; } = string.Empty;
/// <summary> /// <summary>
/// Gets or sets the PublishedServerUriBySubnet /// Gets or sets the PublishedServerUriBySubnet
/// Gets or sets PublishedServerUri to advertise for specific subnets.. /// Gets or sets PublishedServerUri to advertise for specific subnets.
/// </summary> /// </summary>
public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>(); public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>();
/// <summary> /// <summary>
/// Gets or sets a value indicating whether Autodiscovery tracing is enabled.. /// Gets or sets a value indicating whether Autodiscovery tracing is enabled.
/// </summary> /// </summary>
public bool AutoDiscoveryTracing { get; set; } public bool AutoDiscoveryTracing { get; set; }
/// <summary> /// <summary>
/// Gets or sets a value indicating whether Autodiscovery is enabled.. /// Gets or sets a value indicating whether Autodiscovery is enabled.
/// </summary> /// </summary>
public bool AutoDiscovery { get; set; } = true; public bool AutoDiscovery { get; set; } = true;
/// <summary> /// <summary>
/// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>.. /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>.
/// </summary> /// </summary>
public string[] RemoteIPFilter { get; set; } = Array.Empty<string>(); public string[] RemoteIPFilter { get; set; } = Array.Empty<string>();
/// <summary> /// <summary>
/// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist.. /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist.
/// </summary> /// </summary>
public bool IsRemoteIPFilterBlacklist { get; set; } public bool IsRemoteIPFilterBlacklist { get; set; }
/// <summary> /// <summary>
/// Gets or sets a value indicating whether to enable automatic port forwarding.. /// Gets or sets a value indicating whether to enable automatic port forwarding.
/// </summary> /// </summary>
public bool EnableUPnP { get; set; } public bool EnableUPnP { get; set; }
/// <summary> /// <summary>
/// Gets or sets a value indicating whether access outside of the LAN is permitted.. /// Gets or sets a value indicating whether access outside of the LAN is permitted.
/// </summary> /// </summary>
public bool EnableRemoteAccess { get; set; } = true; public bool EnableRemoteAccess { get; set; } = true;
/// <summary> /// <summary>
/// Gets or sets the subnets that are deemed to make up the LAN.. /// Gets or sets the subnets that are deemed to make up the LAN.
/// </summary> /// </summary>
public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>(); public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>();
/// <summary> /// <summary>
/// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.. /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.
/// </summary> /// </summary>
public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>(); public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>();

View File

@ -1,7 +1,6 @@
#pragma warning disable CA1021 // Avoid out parameters
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
@ -13,14 +12,12 @@ using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net; using MediaBrowser.Common.Net;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NetCollection = System.Collections.ObjectModel.Collection<MediaBrowser.Common.Net.IPObject>;
namespace Jellyfin.Networking.Manager namespace Jellyfin.Networking.Manager
{ {
/// <summary> /// <summary>
/// Class to take care of network interface management. /// Class to take care of network interface management.
/// /// Note: The normal collection methods and properties will not work with Collection{IPObject}. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>.
/// Note: The normal collection methods and properties will not work with NetCollection. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>.
/// </summary> /// </summary>
public class NetworkManager : INetworkManager, IDisposable public class NetworkManager : INetworkManager, IDisposable
{ {
@ -37,7 +34,7 @@ namespace Jellyfin.Networking.Manager
/// <summary> /// <summary>
/// List of all interface addresses and masks. /// List of all interface addresses and masks.
/// </summary> /// </summary>
private readonly NetCollection _interfaceAddresses; private readonly Collection<IPObject> _interfaceAddresses;
/// <summary> /// <summary>
/// List of all interface MAC addresses. /// List of all interface MAC addresses.
@ -61,30 +58,30 @@ namespace Jellyfin.Networking.Manager
private bool _eventfire; private bool _eventfire;
/// <summary> /// <summary>
/// Unfiltered user defined LAN subnets. (Configuration.LocalNetworkSubnets). /// Unfiltered user defined LAN subnets. (<see cref="NetworkConfiguration.LocalNetworkSubnets"/>)
/// or internal interface network subnets if undefined by user. /// or internal interface network subnets if undefined by user.
/// </summary> /// </summary>
private NetCollection _lanSubnets; private Collection<IPObject> _lanSubnets;
/// <summary> /// <summary>
/// User defined list of subnets to excluded from the LAN. /// User defined list of subnets to excluded from the LAN.
/// </summary> /// </summary>
private NetCollection _excludedSubnets; private Collection<IPObject> _excludedSubnets;
/// <summary> /// <summary>
/// List of interface addresses to bind the WS. /// List of interface addresses to bind the WS.
/// </summary> /// </summary>
private NetCollection _bindAddresses; private Collection<IPObject> _bindAddresses;
/// <summary> /// <summary>
/// List of interface addresses to exclude from bind. /// List of interface addresses to exclude from bind.
/// </summary> /// </summary>
private NetCollection _bindExclusions; private Collection<IPObject> _bindExclusions;
/// <summary> /// <summary>
/// Caches list of all internal filtered interface addresses and masks. /// Caches list of all internal filtered interface addresses and masks.
/// </summary> /// </summary>
private NetCollection _internalInterfaces; private Collection<IPObject> _internalInterfaces;
/// <summary> /// <summary>
/// Flag set when no custom LAN has been defined in the config. /// Flag set when no custom LAN has been defined in the config.
@ -107,7 +104,7 @@ namespace Jellyfin.Networking.Manager
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); _logger = logger ?? throw new ArgumentNullException(nameof(logger));
_configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager)); _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager));
_interfaceAddresses = new NetCollection(); _interfaceAddresses = new Collection<IPObject>();
_macAddresses = new List<PhysicalAddress>(); _macAddresses = new List<PhysicalAddress>();
_interfaceNames = new Dictionary<string, int>(); _interfaceNames = new Dictionary<string, int>();
_publishedServerUrls = new Dictionary<IPNetAddress, string>(); _publishedServerUrls = new Dictionary<IPNetAddress, string>();
@ -143,7 +140,7 @@ namespace Jellyfin.Networking.Manager
public bool IsIP4Enabled { get; set; } public bool IsIP4Enabled { get; set; }
/// <inheritdoc/> /// <inheritdoc/>
public NetCollection RemoteAddressFilter { get; private set; } public Collection<IPObject> RemoteAddressFilter { get; private set; }
/// <summary> /// <summary>
/// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
@ -160,9 +157,9 @@ namespace Jellyfin.Networking.Manager
/// </summary> /// </summary>
/// <param name="source">Items to assign the collection, or null.</param> /// <param name="source">Items to assign the collection, or null.</param>
/// <returns>The collection created.</returns> /// <returns>The collection created.</returns>
public static NetCollection CreateCollection(IEnumerable<IPObject>? source = null) public static Collection<IPObject> CreateCollection(IEnumerable<IPObject>? source = null)
{ {
var result = new NetCollection(); var result = new Collection<IPObject>();
if (source != null) if (source != null)
{ {
foreach (var item in source) foreach (var item in source)
@ -189,22 +186,22 @@ namespace Jellyfin.Networking.Manager
} }
/// <inheritdoc/> /// <inheritdoc/>
public bool IsGatewayInterface(object? addressObj) public bool IsGatewayInterface(IPObject? addressObj)
{ {
var address = addressObj switch var address = addressObj?.Address ?? IPAddress.None;
{
IPAddress addressIp => addressIp,
IPObject addressIpObj => addressIpObj.Address,
_ => IPAddress.None
};
return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0); return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0);
} }
/// <inheritdoc/> /// <inheritdoc/>
public NetCollection GetLoopbacks() public bool IsGatewayInterface(IPAddress? addressObj)
{ {
NetCollection nc = new NetCollection(); return _internalInterfaces.Any(i => i.Address.Equals(addressObj ?? IPAddress.None) && i.Tag < 0);
}
/// <inheritdoc/>
public Collection<IPObject> GetLoopbacks()
{
Collection<IPObject> nc = new Collection<IPObject>();
if (IsIP4Enabled) if (IsIP4Enabled)
{ {
nc.AddItem(IPAddress.Loopback); nc.AddItem(IPAddress.Loopback);
@ -231,9 +228,9 @@ namespace Jellyfin.Networking.Manager
} }
/// <inheritdoc/> /// <inheritdoc/>
public NetCollection CreateIPCollection(string[] values, bool bracketed = false) public Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false)
{ {
NetCollection col = new NetCollection(); Collection<IPObject> col = new Collection<IPObject>();
if (values == null) if (values == null)
{ {
return col; return col;
@ -256,7 +253,7 @@ namespace Jellyfin.Networking.Manager
{ {
if (bracketed) if (bracketed)
{ {
AddToCollection(col, v.Substring(1)); AddToCollection(col, v[1..]);
} }
} }
else if (!bracketed) else if (!bracketed)
@ -266,7 +263,7 @@ namespace Jellyfin.Networking.Manager
} }
catch (ArgumentException e) catch (ArgumentException e)
{ {
_logger.LogInformation("Ignoring LAN value {value}. Reason : {reason}", v, e.Message); _logger.LogWarning(e, "Ignoring LAN value {value}.", v);
} }
} }
@ -274,7 +271,7 @@ namespace Jellyfin.Networking.Manager
} }
/// <inheritdoc/> /// <inheritdoc/>
public NetCollection GetAllBindInterfaces(bool individualInterfaces = false) public Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false)
{ {
int count = _bindAddresses.Count; int count = _bindAddresses.Count;
@ -288,11 +285,11 @@ namespace Jellyfin.Networking.Manager
if (individualInterfaces) if (individualInterfaces)
{ {
return new NetCollection(_interfaceAddresses); return new Collection<IPObject>(_interfaceAddresses);
} }
// No bind address and no exclusions, so listen on all interfaces. // No bind address and no exclusions, so listen on all interfaces.
NetCollection result = new NetCollection(); Collection<IPObject> result = new Collection<IPObject>();
if (IsIP4Enabled) if (IsIP4Enabled)
{ {
@ -376,7 +373,7 @@ namespace Jellyfin.Networking.Manager
if (MatchesPublishedServerUrl(source, isExternal, out string res, out port)) if (MatchesPublishedServerUrl(source, isExternal, out string res, out port))
{ {
_logger.LogInformation("{0}: Using BindAddress {1}:{2}", source, res, port); _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port);
return res; return res;
} }
} }
@ -429,7 +426,7 @@ namespace Jellyfin.Networking.Manager
} }
/// <inheritdoc/> /// <inheritdoc/>
public NetCollection GetInternalBindAddresses() public Collection<IPObject> GetInternalBindAddresses()
{ {
int count = _bindAddresses.Count; int count = _bindAddresses.Count;
@ -445,7 +442,7 @@ namespace Jellyfin.Networking.Manager
return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback())); return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback()));
} }
return new NetCollection(_bindAddresses); return new Collection<IPObject>(_bindAddresses);
} }
/// <inheritdoc/> /// <inheritdoc/>
@ -526,7 +523,7 @@ namespace Jellyfin.Networking.Manager
} }
/// <inheritdoc/> /// <inheritdoc/>
public NetCollection GetFilteredLANSubnets(NetCollection? filter = null) public Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null)
{ {
if (filter == null) if (filter == null)
{ {
@ -543,7 +540,7 @@ namespace Jellyfin.Networking.Manager
} }
/// <inheritdoc/> /// <inheritdoc/>
public bool TryParseInterface(string token, out NetCollection? result) public bool TryParseInterface(string token, out Collection<IPObject>? result)
{ {
result = null; result = null;
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
@ -553,16 +550,16 @@ namespace Jellyfin.Networking.Manager
if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index)) if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index))
{ {
result = new NetCollection(); result = new Collection<IPObject>();
_logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token); _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token);
// Replace interface tags with the interface IP's. // Replace interface tags with the interface IP's.
foreach (IPNetAddress iface in _interfaceAddresses) foreach (IPNetAddress iface in _interfaceAddresses)
{ {
if (Math.Abs(iface.Tag) == index && if (Math.Abs(iface.Tag) == index
((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
(IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
{ {
result.AddItem(iface); result.AddItem(iface);
} }
@ -577,8 +574,8 @@ namespace Jellyfin.Networking.Manager
/// <summary> /// <summary>
/// Reloads all settings and re-initialises the instance. /// Reloads all settings and re-initialises the instance.
/// </summary> /// </summary>
/// <param name="configuration">The configuration to use.</param> /// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param>
public void UpdateSettings(object configuration) public void UpdateSettings(NetworkConfiguration configuration)
{ {
NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration));
@ -622,7 +619,7 @@ namespace Jellyfin.Networking.Manager
/// <summary> /// <summary>
/// Protected implementation of Dispose pattern. /// Protected implementation of Dispose pattern.
/// </summary> /// </summary>
/// <param name="disposing">True to dispose the managed state.</param> /// <param name="disposing"><c>True</c> to dispose the managed state.</param>
protected virtual void Dispose(bool disposing) protected virtual void Dispose(bool disposing)
{ {
if (!_disposed) if (!_disposed)
@ -639,11 +636,11 @@ namespace Jellyfin.Networking.Manager
} }
/// <summary> /// <summary>
/// Trys to identify the string and return an object of that class. /// Tries to identify the string and return an object of that class.
/// </summary> /// </summary>
/// <param name="addr">String to parse.</param> /// <param name="addr">String to parse.</param>
/// <param name="result">IPObject to return.</param> /// <param name="result">IPObject to return.</param>
/// <returns>True if the value parsed successfully.</returns> /// <returns><c>true</c> if the value parsed successfully, <c>false</c> otherwise.</returns>
private static bool TryParse(string addr, out IPObject result) private static bool TryParse(string addr, out IPObject result)
{ {
if (!string.IsNullOrEmpty(addr)) if (!string.IsNullOrEmpty(addr))
@ -671,7 +668,7 @@ namespace Jellyfin.Networking.Manager
/// Ipv6 addresses are returned in [ ], with their scope removed. /// Ipv6 addresses are returned in [ ], with their scope removed.
/// </summary> /// </summary>
/// <param name="address">Address to convert.</param> /// <param name="address">Address to convert.</param>
/// <returns>URI save conversion of the address.</returns> /// <returns>URI safe conversion of the address.</returns>
private static string FormatIP6String(IPAddress address) private static string FormatIP6String(IPAddress address)
{ {
var str = address.ToString(); var str = address.ToString();
@ -694,7 +691,7 @@ namespace Jellyfin.Networking.Manager
{ {
if (evt.Key.Equals("network", StringComparison.Ordinal)) if (evt.Key.Equals("network", StringComparison.Ordinal))
{ {
UpdateSettings(evt.NewConfiguration); UpdateSettings((NetworkConfiguration)evt.NewConfiguration);
} }
} }
@ -703,7 +700,7 @@ namespace Jellyfin.Networking.Manager
/// </summary> /// </summary>
/// <param name="token">String to check.</param> /// <param name="token">String to check.</param>
/// <param name="index">Interface index number.</param> /// <param name="index">Interface index number.</param>
/// <returns>True if an interface name matches the token.</returns> /// <returns><c>true</c> if an interface name matches the token, <c>False</c> otherwise.</returns>
private bool IsInterface(string token, out int index) private bool IsInterface(string token, out int index)
{ {
index = -1; index = -1;
@ -720,8 +717,8 @@ namespace Jellyfin.Networking.Manager
foreach ((string interfc, int interfcIndex) in _interfaceNames) foreach ((string interfc, int interfcIndex) in _interfaceNames)
{ {
if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) || if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase))
(partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture)))
{ {
index = interfcIndex; index = interfcIndex;
return true; return true;
@ -733,11 +730,11 @@ namespace Jellyfin.Networking.Manager
} }
/// <summary> /// <summary>
/// Parses strings into the collection, replacing any interface references. /// Parses a string and adds it into the the collection, replacing any interface references.
/// </summary> /// </summary>
/// <param name="col">Collection.</param> /// <param name="col"><see cref="Collection{IPObject}"/>Collection.</param>
/// <param name="token">String to parse.</param> /// <param name="token">String value to parse.</param>
private void AddToCollection(NetCollection col, string token) private void AddToCollection(Collection<IPObject> col, string token)
{ {
// Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
// Null check required here for automated testing. // Null check required here for automated testing.
@ -748,9 +745,9 @@ namespace Jellyfin.Networking.Manager
// Replace interface tags with the interface IP's. // Replace interface tags with the interface IP's.
foreach (IPNetAddress iface in _interfaceAddresses) foreach (IPNetAddress iface in _interfaceAddresses)
{ {
if (Math.Abs(iface.Tag) == index && if (Math.Abs(iface.Tag) == index
((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork)
(IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
{ {
col.AddItem(iface); col.AddItem(iface);
} }
@ -791,7 +788,7 @@ namespace Jellyfin.Networking.Manager
/// Handler for network change events. /// Handler for network change events.
/// </summary> /// </summary>
/// <param name="sender">Sender.</param> /// <param name="sender">Sender.</param>
/// <param name="e">Network availability information.</param> /// <param name="e">A <see cref="NetworkAvailabilityEventArgs"/> containing network availability information.</param>
private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e)
{ {
_logger.LogDebug("Network availability changed."); _logger.LogDebug("Network availability changed.");
@ -802,7 +799,7 @@ namespace Jellyfin.Networking.Manager
/// Handler for network change events. /// Handler for network change events.
/// </summary> /// </summary>
/// <param name="sender">Sender.</param> /// <param name="sender">Sender.</param>
/// <param name="e">Event arguments.</param> /// <param name="e">An <see cref="EventArgs"/>.</param>
private void OnNetworkAddressChanged(object? sender, EventArgs e) private void OnNetworkAddressChanged(object? sender, EventArgs e)
{ {
_logger.LogDebug("Network address change detected."); _logger.LogDebug("Network address change detected.");
@ -812,7 +809,7 @@ namespace Jellyfin.Networking.Manager
/// <summary> /// <summary>
/// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession.
/// </summary> /// </summary>
/// <returns>The network change async.</returns> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
private async Task OnNetworkChangeAsync() private async Task OnNetworkChangeAsync()
{ {
try try
@ -883,7 +880,7 @@ namespace Jellyfin.Networking.Manager
{ {
_publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement; _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement;
} }
else if (TryParseInterface(parts[0], out NetCollection? addresses) && addresses != null) else if (TryParseInterface(parts[0], out Collection<IPObject>? addresses) && addresses != null)
{ {
foreach (IPNetAddress na in addresses) foreach (IPNetAddress na in addresses)
{ {
@ -903,6 +900,9 @@ namespace Jellyfin.Networking.Manager
} }
} }
/// <summary>
/// Initialises the network bind addresses.
/// </summary>
private void InitialiseBind(NetworkConfiguration config) private void InitialiseBind(NetworkConfiguration config)
{ {
string[] lanAddresses = config.LocalNetworkAddresses; string[] lanAddresses = config.LocalNetworkAddresses;
@ -931,6 +931,9 @@ namespace Jellyfin.Networking.Manager
_logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString()); _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString());
} }
/// <summary>
/// Initialises the remote address values.
/// </summary>
private void InitialiseRemote(NetworkConfiguration config) private void InitialiseRemote(NetworkConfiguration config)
{ {
RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter); RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter);
@ -964,7 +967,7 @@ namespace Jellyfin.Networking.Manager
_internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i))); _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i)));
// Subnets are the same as the calculated internal interface. // Subnets are the same as the calculated internal interface.
_lanSubnets = new NetCollection(); _lanSubnets = new Collection<IPObject>();
// We must listen on loopback for LiveTV to function regardless of the settings. // We must listen on loopback for LiveTV to function regardless of the settings.
if (IsIP6Enabled) if (IsIP6Enabled)
@ -1131,7 +1134,7 @@ namespace Jellyfin.Networking.Manager
/// <param name="isExternal">True if the source is in the external subnet.</param> /// <param name="isExternal">True if the source is in the external subnet.</param>
/// <param name="bindPreference">The published server url that matches the source address.</param> /// <param name="bindPreference">The published server url that matches the source address.</param>
/// <param name="port">The resultant port, if one exists.</param> /// <param name="port">The resultant port, if one exists.</param>
/// <returns>True if a match is found.</returns> /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, out string bindPreference, out int? port) private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, out string bindPreference, out int? port)
{ {
bindPreference = string.Empty; bindPreference = string.Empty;
@ -1185,7 +1188,7 @@ namespace Jellyfin.Networking.Manager
/// <param name="source">IP source address to use.</param> /// <param name="source">IP source address to use.</param>
/// <param name="isExternal">True if the source is in the external subnet.</param> /// <param name="isExternal">True if the source is in the external subnet.</param>
/// <param name="result">The result, if a match is found.</param> /// <param name="result">The result, if a match is found.</param>
/// <returns>True if a match is found.</returns> /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
private bool MatchesBindInterface(IPObject source, bool isExternal, out string result) private bool MatchesBindInterface(IPObject source, bool isExternal, out string result)
{ {
result = string.Empty; result = string.Empty;
@ -1202,7 +1205,7 @@ namespace Jellyfin.Networking.Manager
{ {
// Check to see if any of the bind interfaces are in the same subnet. // Check to see if any of the bind interfaces are in the same subnet.
NetCollection bindResult; Collection<IPObject> bindResult;
IPAddress? defaultGateway = null; IPAddress? defaultGateway = null;
IPAddress? bindAddress; IPAddress? bindAddress;
@ -1246,7 +1249,6 @@ namespace Jellyfin.Networking.Manager
if (isExternal) if (isExternal)
{ {
// TODO: remove this after testing.
_logger.LogWarning("{0}: External request received, however, only an internal interface bind found.", source); _logger.LogWarning("{0}: External request received, however, only an internal interface bind found.", source);
} }
@ -1261,7 +1263,7 @@ namespace Jellyfin.Networking.Manager
/// </summary> /// </summary>
/// <param name="source">IP source address to use.</param> /// <param name="source">IP source address to use.</param>
/// <param name="result">The result, if a match is found.</param> /// <param name="result">The result, if a match is found.</param>
/// <returns>True if a match is found.</returns> /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
private bool MatchesExternalInterface(IPObject source, out string result) private bool MatchesExternalInterface(IPObject source, out string result)
{ {
result = string.Empty; result = string.Empty;
@ -1292,7 +1294,6 @@ namespace Jellyfin.Networking.Manager
// Have to return something, so return an internal address // Have to return something, so return an internal address
// TODO: remove this after testing.
_logger.LogWarning("{0}: External request received, however, no WAN interface found.", source); _logger.LogWarning("{0}: External request received, however, no WAN interface found.", source);
return false; return false;
} }

View File

@ -1,10 +1,11 @@
#nullable enable #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; using Microsoft.AspNetCore.Http;
using NetCollection = System.Collections.ObjectModel.Collection<MediaBrowser.Common.Net.IPObject>;
namespace MediaBrowser.Common.Net namespace MediaBrowser.Common.Net
{ {
@ -31,7 +32,7 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Gets the remote address filter. /// Gets the remote address filter.
/// </summary> /// </summary>
NetCollection RemoteAddressFilter { get; } Collection<IPObject> RemoteAddressFilter { get; }
/// <summary> /// <summary>
/// Gets or sets a value indicating whether iP6 is enabled. /// Gets or sets a value indicating whether iP6 is enabled.
@ -46,17 +47,17 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Calculates the list of interfaces to use for Kestrel. /// Calculates the list of interfaces to use for Kestrel.
/// </summary> /// </summary>
/// <returns>A NetCollection object containing all the interfaces to bind. /// <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 /// If all the interfaces are specified, and none are excluded, it returns zero items
/// to represent any address.</returns> /// to represent any address.</returns>
/// <param name="individualInterfaces">When false, return <see cref="IPAddress.Any"/> or <see cref="IPAddress.IPv6Any"/> for all interfaces.</param> /// <param name="individualInterfaces">When false, return <see cref="IPAddress.Any"/> or <see cref="IPAddress.IPv6Any"/> for all interfaces.</param>
NetCollection GetAllBindInterfaces(bool individualInterfaces = false); Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false);
/// <summary> /// <summary>
/// Returns a collection containing the loopback interfaces. /// Returns a collection containing the loopback interfaces.
/// </summary> /// </summary>
/// <returns>Netcollection.</returns> /// <returns>Collection{IPObject}.</returns>
NetCollection GetLoopbacks(); Collection<IPObject> GetLoopbacks();
/// <summary> /// <summary>
/// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
@ -137,7 +138,14 @@ namespace MediaBrowser.Common.Net
/// </summary> /// </summary>
/// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param> /// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
/// <returns>Result of the check.</returns> /// <returns>Result of the check.</returns>
bool IsGatewayInterface(object? addressObj); 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> /// <summary>
/// Returns true if the address is a private address. /// Returns true if the address is a private address.
@ -178,21 +186,21 @@ namespace MediaBrowser.Common.Net
/// <param name="token">Token to parse.</param> /// <param name="token">Token to parse.</param>
/// <param name="result">Resultant object's ip addresses, if successful.</param> /// <param name="result">Resultant object's ip addresses, if successful.</param>
/// <returns>Success of the operation.</returns> /// <returns>Success of the operation.</returns>
bool TryParseInterface(string token, out NetCollection? result); bool TryParseInterface(string token, out Collection<IPObject>? result);
/// <summary> /// <summary>
/// Parses an array of strings into a NetCollection. /// Parses an array of strings into a Collection{IPObject}.
/// </summary> /// </summary>
/// <param name="values">Values to parse.</param> /// <param name="values">Values to parse.</param>
/// <param name="bracketed">When true, only include values in []. When false, ignore bracketed values.</param> /// <param name="bracketed">When true, only include values in []. When false, ignore bracketed values.</param>
/// <returns>IPCollection object containing the value strings.</returns> /// <returns>IPCollection object containing the value strings.</returns>
NetCollection CreateIPCollection(string[] values, bool bracketed = false); Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false);
/// <summary> /// <summary>
/// Returns all the internal Bind interface addresses. /// Returns all the internal Bind interface addresses.
/// </summary> /// </summary>
/// <returns>An internal list of interfaces addresses.</returns> /// <returns>An internal list of interfaces addresses.</returns>
NetCollection GetInternalBindAddresses(); Collection<IPObject> GetInternalBindAddresses();
/// <summary> /// <summary>
/// Checks to see if an IP address is still a valid interface address. /// Checks to see if an IP address is still a valid interface address.
@ -220,12 +228,6 @@ namespace MediaBrowser.Common.Net
/// </summary> /// </summary>
/// <param name="filter">Optional filter for the list.</param> /// <param name="filter">Optional filter for the list.</param>
/// <returns>Returns a filtered list of LAN addresses.</returns> /// <returns>Returns a filtered list of LAN addresses.</returns>
NetCollection GetFilteredLANSubnets(NetCollection? filter = null); Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null);
/// <summary>
/// Reloads all settings and re-initialises the instance.
/// </summary>
/// <param name="configuration">The configuration to use.</param>
void UpdateSettings(object configuration);
} }
} }

View File

@ -19,7 +19,7 @@ namespace MediaBrowser.Common.Net
public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None); public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None);
/// <summary> /// <summary>
/// Time when last resolved. /// Time when last resolved in ticks.
/// </summary> /// </summary>
private long _lastResolved; private long _lastResolved;
@ -63,7 +63,8 @@ namespace MediaBrowser.Common.Net
set set
{ {
// Not implemented. // Not implemented, as a host's address is determined by DNS.
throw new NotImplementedException("The address of a host is determined by DNS.");
} }
} }
@ -75,12 +76,14 @@ namespace MediaBrowser.Common.Net
{ {
get get
{ {
return (byte)(ResolveHost() ? 128 : 0); return (byte)(ResolveHost() ? 128 : 32);
} }
set set
{ {
// Not implemented. // 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.
throw new NotImplementedException("The prefix length on a host cannot be set.");
} }
} }
@ -92,13 +95,7 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Gets a value indicating whether the address has a value. /// Gets a value indicating whether the address has a value.
/// </summary> /// </summary>
public bool HasAddress public bool HasAddress => _addresses.Length != 0;
{
get
{
return _addresses.Length > 0;
}
}
/// <summary> /// <summary>
/// Gets the host name of this object. /// Gets the host name of this object.
@ -128,7 +125,7 @@ namespace MediaBrowser.Common.Net
/// </summary> /// </summary>
/// <param name="host">Host name to parse.</param> /// <param name="host">Host name to parse.</param>
/// <param name="hostObj">Object representing the string, if it has successfully been parsed.</param> /// <param name="hostObj">Object representing the string, if it has successfully been parsed.</param>
/// <returns>Success result of the parsing.</returns> /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns>
public static bool TryParse(string host, out IPHost hostObj) public static bool TryParse(string host, out IPHost hostObj)
{ {
if (!string.IsNullOrEmpty(host)) if (!string.IsNullOrEmpty(host))
@ -142,7 +139,7 @@ namespace MediaBrowser.Common.Net
else else
{ {
// See if it's an IPv6 in [] with no port. // See if it's an IPv6 in [] with no port.
i = host.IndexOf("]", StringComparison.OrdinalIgnoreCase); i = host.IndexOf(']', StringComparison.OrdinalIgnoreCase);
if (i != -1) if (i != -1)
{ {
return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj);
@ -394,19 +391,19 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Attempt to resolve the ip address of a host. /// Attempt to resolve the ip address of a host.
/// </summary> /// </summary>
/// <returns>The result of the comparison function.</returns> /// <returns><c>true</c> if any addresses have been resolved, otherwise <c>false</c>.</returns>
private bool ResolveHost() private bool ResolveHost()
{ {
// When was the last time we resolved? // When was the last time we resolved?
if (_lastResolved == 0) if (_lastResolved == 0)
{ {
_lastResolved = DateTime.Now.Ticks; _lastResolved = DateTime.UtcNow.Ticks;
} }
// If we haven't resolved before, or out timer has run out... // If we haven't resolved before, or out timer has run out...
if ((_addresses.Length == 0 && !Resolved) || (TimeSpan.FromTicks(DateTime.Now.Ticks - _lastResolved).TotalMinutes > Timeout)) if ((_addresses.Length == 0 && !Resolved) || (TimeSpan.FromTicks(DateTime.UtcNow.Ticks - _lastResolved).TotalMinutes > Timeout))
{ {
_lastResolved = DateTime.Now.Ticks; _lastResolved = DateTime.UtcNow.Ticks;
ResolveHostInternal().GetAwaiter().GetResult(); ResolveHostInternal().GetAwaiter().GetResult();
Resolved = true; Resolved = true;
} }
@ -417,7 +414,7 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Task that looks up a Host name and returns its IP addresses. /// Task that looks up a Host name and returns its IP addresses.
/// </summary> /// </summary>
/// <returns>Array of IPAddress objects.</returns> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
private async Task ResolveHostInternal() private async Task ResolveHostInternal()
{ {
if (!string.IsNullOrEmpty(HostName)) if (!string.IsNullOrEmpty(HostName))

View File

@ -26,7 +26,7 @@ namespace MediaBrowser.Common.Net
private IPObject? _networkAddress; private IPObject? _networkAddress;
/// <summary> /// <summary>
/// Gets or sets the user defined functions that need storage in this object. /// Gets or sets a user defined value that is associated with this object.
/// </summary> /// </summary>
public int Tag { get; set; } public int Tag { get; set; }
@ -38,18 +38,7 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Gets the object's network address. /// Gets the object's network address.
/// </summary> /// </summary>
public IPObject NetworkAddress public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress();
{
get
{
if (_networkAddress == null)
{
_networkAddress = CalculateNetworkAddress();
}
return _networkAddress;
}
}
/// <summary> /// <summary>
/// Gets or sets the object's IP address. /// Gets or sets the object's IP address.
@ -92,22 +81,33 @@ namespace MediaBrowser.Common.Net
return (Address: address, PrefixLength: prefixLength); return (Address: address, PrefixLength: 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.
byte[] addressBytes = address.GetAddressBytes(); byte[] addressBytes = address.GetAddressBytes();
int div = prefixLength / 8; int div = prefixLength / 8;
int mod = prefixLength % 8; int mod = prefixLength % 8;
if (mod != 0) if (mod != 0)
{ {
// Prefix length is counted right to left, so subtract 8 so we know how many bits to clear.
mod = 8 - mod; 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); addressBytes[div] = (byte)((int)addressBytes[div] >> mod << mod);
// Move on the next byte.
div++; 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++) for (int octet = div; octet < addressBytes.Length; octet++)
{ {
addressBytes[octet] = 0; addressBytes[octet] = 0;
} }
// Return the network address for the prefix.
return (Address: new IPAddress(addressBytes), PrefixLength: prefixLength); return (Address: new IPAddress(addressBytes), PrefixLength: prefixLength);
} }
@ -179,18 +179,18 @@ namespace MediaBrowser.Common.Net
byte[] octet = address.GetAddressBytes(); byte[] octet = address.GetAddressBytes();
return (octet[0] == 10) || return (octet[0] == 10)
(octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) || // RFC1918 || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918
(octet[0] == 192 && octet[1] == 168) || // RFC1918 || (octet[0] == 192 && octet[1] == 168) // RFC1918
(octet[0] == 127); // RFC1122 || (octet[0] == 127); // RFC1122
} }
else else
{ {
byte[] octet = address.GetAddressBytes(); byte[] octet = address.GetAddressBytes();
uint word = (uint)(octet[0] << 8) + octet[1]; uint word = (uint)(octet[0] << 8) + octet[1];
return (word >= 0xfe80 && word <= 0xfebf) || // fe80::/10 :Local link. return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link.
(word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address. || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address.
} }
} }
@ -202,7 +202,8 @@ namespace MediaBrowser.Common.Net
/// </summary> /// </summary>
/// <param name="address">IPAddress object to check.</param> /// <param name="address">IPAddress object to check.</param>
/// <returns>True if it is a local link address.</returns> /// <returns>True if it is a local link address.</returns>
/// <remarks>See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress /// <remarks>
/// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress
/// it appears that the IPAddress.IsIPv6LinkLocal is out of date. /// it appears that the IPAddress.IsIPv6LinkLocal is out of date.
/// </remarks> /// </remarks>
public static bool IsIPv6LinkLocal(IPAddress address) public static bool IsIPv6LinkLocal(IPAddress address)
@ -237,11 +238,10 @@ namespace MediaBrowser.Common.Net
public static IPAddress CidrToMask(byte cidr, AddressFamily family) public static IPAddress CidrToMask(byte cidr, AddressFamily family)
{ {
uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr); uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr);
addr = addr = ((addr & 0xff000000) >> 24)
((addr & 0xff000000) >> 24) | | ((addr & 0x00ff0000) >> 8)
((addr & 0x00ff0000) >> 8) | | ((addr & 0x0000ff00) << 8)
((addr & 0x0000ff00) << 8) | | ((addr & 0x000000ff) << 24);
((addr & 0x000000ff) << 24);
return new IPAddress(addr); return new IPAddress(addr);
} }
@ -304,7 +304,7 @@ namespace MediaBrowser.Common.Net
/// <param name="family">Type of address to remove.</param> /// <param name="family">Type of address to remove.</param>
public virtual void Remove(AddressFamily family) public virtual void Remove(AddressFamily family)
{ {
// This method only peforms a function in the IPHost implementation of IPObject. // This method only performs a function in the IPHost implementation of IPObject.
} }
/// <summary> /// <summary>
@ -352,9 +352,9 @@ namespace MediaBrowser.Common.Net
/// <returns>Equality result.</returns> /// <returns>Equality result.</returns>
public virtual bool Equals(IPObject? other) public virtual bool Equals(IPObject? other)
{ {
if (other != null && other is IPObject otherObj) if (other != null)
{ {
return !Address.Equals(IPAddress.None) && Address.Equals(otherObj.Address); return !Address.Equals(IPAddress.None) && Address.Equals(other.Address);
} }
return false; return false;

View File

@ -2,10 +2,10 @@
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net; using System.Net;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using System.Text; using System.Text;
using NetCollection = System.Collections.ObjectModel.Collection<MediaBrowser.Common.Net.IPObject>;
namespace MediaBrowser.Common.Net namespace MediaBrowser.Common.Net
{ {
@ -17,9 +17,9 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Add an address to the collection. /// Add an address to the collection.
/// </summary> /// </summary>
/// <param name="source">The <see cref="NetCollection"/>.</param> /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
/// <param name="ip">Item to add.</param> /// <param name="ip">Item to add.</param>
public static void AddItem(this NetCollection source, IPAddress ip) public static void AddItem(this Collection<IPObject> source, IPAddress ip)
{ {
if (!source.ContainsAddress(ip)) if (!source.ContainsAddress(ip))
{ {
@ -30,9 +30,9 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Adds a network to the collection. /// Adds a network to the collection.
/// </summary> /// </summary>
/// <param name="source">The <see cref="NetCollection"/>.</param> /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
/// <param name="item">Item to add.</param> /// <param name="item">Item to add.</param>
public static void AddItem(this NetCollection source, IPObject item) public static void AddItem(this Collection<IPObject> source, IPObject item)
{ {
if (!source.ContainsAddress(item)) if (!source.ContainsAddress(item))
{ {
@ -43,33 +43,21 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Converts this object to a string. /// Converts this object to a string.
/// </summary> /// </summary>
/// <param name="source">The <see cref="NetCollection"/>.</param> /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
/// <returns>Returns a string representation of this object.</returns> /// <returns>Returns a string representation of this object.</returns>
public static string AsString(this NetCollection source) public static string AsString(this Collection<IPObject> source)
{ {
var sb = new StringBuilder(); return $"[{string.Join(',', source)}]";
string output = "[";
if (source.Count > 0)
{
foreach (var i in source)
{
output += $"{i},";
}
output = output[0..^1];
}
return $"{output}]";
} }
/// <summary> /// <summary>
/// Returns true if the collection contains an item with the ip address, /// 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. /// or the ip address falls within any of the collection's network ranges.
/// </summary> /// </summary>
/// <param name="source">The <see cref="NetCollection"/>.</param> /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
/// <param name="item">The item to look for.</param> /// <param name="item">The item to look for.</param>
/// <returns>True if the collection contains the item.</returns> /// <returns>True if the collection contains the item.</returns>
public static bool ContainsAddress(this NetCollection source, IPAddress item) public static bool ContainsAddress(this Collection<IPObject> source, IPAddress item)
{ {
if (source.Count == 0) if (source.Count == 0)
{ {
@ -101,10 +89,10 @@ namespace MediaBrowser.Common.Net
/// Returns true if the collection contains an item with the ip address, /// 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. /// or the ip address falls within any of the collection's network ranges.
/// </summary> /// </summary>
/// <param name="source">The <see cref="NetCollection"/>.</param> /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
/// <param name="item">The item to look for.</param> /// <param name="item">The item to look for.</param>
/// <returns>True if the collection contains the item.</returns> /// <returns>True if the collection contains the item.</returns>
public static bool ContainsAddress(this NetCollection source, IPObject item) public static bool ContainsAddress(this Collection<IPObject> source, IPObject item)
{ {
if (source.Count == 0) if (source.Count == 0)
{ {
@ -128,12 +116,12 @@ namespace MediaBrowser.Common.Net
} }
/// <summary> /// <summary>
/// Compares two NetCollection objects. The order is ignored. /// Compares two Collection{IPObject} objects. The order is ignored.
/// </summary> /// </summary>
/// <param name="source">The <see cref="NetCollection"/>.</param> /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
/// <param name="dest">Item to compare to.</param> /// <param name="dest">Item to compare to.</param>
/// <returns>True if both are equal.</returns> /// <returns>True if both are equal.</returns>
public static bool Compare(this NetCollection source, NetCollection dest) public static bool Compare(this Collection<IPObject> source, Collection<IPObject> dest)
{ {
if (dest == null || source.Count != dest.Count) if (dest == null || source.Count != dest.Count)
{ {
@ -164,16 +152,16 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Returns a collection containing the subnets of this collection given. /// Returns a collection containing the subnets of this collection given.
/// </summary> /// </summary>
/// <param name="source">The <see cref="NetCollection"/>.</param> /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
/// <returns>NetCollection object containing the subnets.</returns> /// <returns>Collection{IPObject} object containing the subnets.</returns>
public static NetCollection AsNetworks(this NetCollection source) public static Collection<IPObject> AsNetworks(this Collection<IPObject> source)
{ {
if (source == null) if (source == null)
{ {
throw new ArgumentNullException(nameof(source)); throw new ArgumentNullException(nameof(source));
} }
NetCollection res = new NetCollection(); Collection<IPObject> res = new Collection<IPObject>();
foreach (IPObject i in source) foreach (IPObject i in source)
{ {
@ -184,10 +172,10 @@ namespace MediaBrowser.Common.Net
na.Tag = i.Tag; na.Tag = i.Tag;
res.AddItem(na); res.AddItem(na);
} }
else else if (i is IPHost ipHost)
{ {
// Flatten out IPHost and add all its ip addresses. // Flatten out IPHost and add all its ip addresses.
foreach (var addr in ((IPHost)i).GetAddresses()) foreach (var addr in ipHost.GetAddresses())
{ {
IPNetAddress host = new IPNetAddress(addr) IPNetAddress host = new IPNetAddress(addr)
{ {
@ -205,17 +193,17 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Excludes all the items from this list that are found in excludeList. /// Excludes all the items from this list that are found in excludeList.
/// </summary> /// </summary>
/// <param name="source">The <see cref="NetCollection"/>.</param> /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
/// <param name="excludeList">Items to exclude.</param> /// <param name="excludeList">Items to exclude.</param>
/// <returns>A new collection, with the items excluded.</returns> /// <returns>A new collection, with the items excluded.</returns>
public static NetCollection Exclude(this NetCollection source, NetCollection excludeList) public static Collection<IPObject> Exclude(this Collection<IPObject> source, Collection<IPObject> excludeList)
{ {
if (source.Count == 0 || excludeList == null) if (source.Count == 0 || excludeList == null)
{ {
return new NetCollection(source); return new Collection<IPObject>(source);
} }
NetCollection results = new NetCollection(); Collection<IPObject> results = new Collection<IPObject>();
bool found; bool found;
foreach (var outer in source) foreach (var outer in source)
@ -243,14 +231,14 @@ namespace MediaBrowser.Common.Net
/// <summary> /// <summary>
/// Returns all items that co-exist in this object and target. /// Returns all items that co-exist in this object and target.
/// </summary> /// </summary>
/// <param name="source">The <see cref="NetCollection"/>.</param> /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
/// <param name="target">Collection to compare with.</param> /// <param name="target">Collection to compare with.</param>
/// <returns>A collection containing all the matches.</returns> /// <returns>A collection containing all the matches.</returns>
public static NetCollection Union(this NetCollection source, NetCollection target) public static Collection<IPObject> Union(this Collection<IPObject> source, Collection<IPObject> target)
{ {
if (source.Count == 0) if (source.Count == 0)
{ {
return new NetCollection(); return new Collection<IPObject>();
} }
if (target == null) if (target == null)
@ -258,7 +246,7 @@ namespace MediaBrowser.Common.Net
throw new ArgumentNullException(nameof(target)); throw new ArgumentNullException(nameof(target));
} }
NetCollection nc = new NetCollection(); Collection<IPObject> nc = new Collection<IPObject>();
foreach (IPObject i in source) foreach (IPObject i in source)
{ {