Updated NetworkManager to PR1

This commit is contained in:
Greenback 2020-10-08 19:00:30 +01:00
parent 2e3901252a
commit a3f0843ac9
5 changed files with 338 additions and 85 deletions

View File

@ -0,0 +1,223 @@
#pragma warning disable CA1819 // Properties should not return arrays
using System;
using MediaBrowser.Model.Configuration;
namespace Jellyfin.Networking.Configuration
{
/// <summary>
/// Defines the <see cref="NetworkConfiguration" />.
/// </summary>
public class NetworkConfiguration
{
private string _baseUrl = string.Empty;
/// <summary>
/// Gets the default http port.
/// </summary>
public const int DefaultHttpPort = 8096;
/// <summary>
/// Gets the default https port.
/// </summary>
public const int DefaultHttpsPort = 8920;
/// <summary>
/// Gets or sets a value indicating whether the server should force connections over HTTPS.
/// </summary>
public bool RequireHttps { get; set; } = false;
/// <summary>
/// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at.
/// </summary>
public string BaseUrl
{
get => _baseUrl;
set
{
// Normalize the start of the string
if (string.IsNullOrWhiteSpace(value))
{
// If baseUrl is empty, set an empty prefix string
_baseUrl = string.Empty;
return;
}
if (value[0] != '/')
{
// If baseUrl was not configured with a leading slash, append one for consistency
value = "/" + value;
}
// Normalize the end of the string
if (value[value.Length - 1] == '/')
{
// If baseUrl was configured with a trailing slash, remove it for consistency
value = value.Remove(value.Length - 1);
}
_baseUrl = value;
}
}
/// <summary>
/// Gets or sets the public HTTPS port.
/// </summary>
/// <value>The public HTTPS port.</value>
public int PublicHttpsPort { get; set; } = DefaultHttpsPort;
/// <summary>
/// Gets or sets the HTTP server port number.
/// </summary>
/// <value>The HTTP server port number.</value>
public int HttpServerPortNumber { get; set; } = DefaultHttpPort;
/// <summary>
/// Gets or sets the HTTPS server port number.
/// </summary>
/// <value>The HTTPS server port number.</value>
public int HttpsPortNumber { get; set; } = DefaultHttpsPort;
/// <summary>
/// Gets or sets a value indicating whether to use HTTPS.
/// </summary>
/// <remarks>
/// In order for HTTPS to be used, in addition to setting this to true, valid values must also be
/// provided for <see cref="ServerConfiguration.CertificatePath"/> and <see cref="ServerConfiguration.CertificatePassword"/>.
/// </remarks>
public bool EnableHttps { get; set; } = false;
/// <summary>
/// Gets or sets the public mapped port.
/// </summary>
/// <value>The public mapped port.</value>
public int PublicPort { get; set; } = DefaultHttpPort;
/// <summary>
/// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding..
/// </summary>
public bool UPnPCreateHttpPortMap { get; set; } = false;
/// <summary>
/// Gets or sets the UDPPortRange
/// Gets or sets client udp port range..
/// </summary>
public string UDPPortRange { get; set; } = string.Empty;
/// <summary>
/// Gets or sets a value indicating whether gets or sets IPV6 capability..
/// </summary>
public bool EnableIPV6 { get; set; } = false;
/// <summary>
/// Gets or sets a value indicating whether gets or sets IPV4 capability..
/// </summary>
public bool EnableIPV4 { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether detailed ssdp logs are sent to the console/log.
/// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work..
/// </summary>
public bool EnableSSDPTracing { get; set; } = false;
/// <summary>
/// Gets or sets the SSDPTracingFilter
/// Gets or sets a value indicating whether an IP address is to be used to filter the detailed ssdp logs that are being sent to the console/log.
/// If the setting "Emby.Dlna": "Debug" msut be set in logging.default.json for this property to work..
/// </summary>
public string SSDPTracingFilter { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the number of times SSDP UDP messages are sent..
/// </summary>
public int UDPSendCount { get; set; } = 2;
/// <summary>
/// Gets or sets the delay between each groups of SSDP messages (in ms)..
/// </summary>
public int UDPSendDelay { get; set; } = 100;
/// <summary>
/// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be Ignore for the purposes of binding..
/// </summary>
public bool IgnoreVirtualInterfaces { get; set; } = true;
/// <summary>
/// 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"/>..
/// </summary>
public string VirtualInterfaceNames { get; set; } = "vEthernet*";
/// <summary>
/// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor..
/// </summary>
public int GatewayMonitorPeriod { get; set; } = 60;
/// <summary>
/// Gets a value indicating whether multi-socket binding is available..
/// </summary>
public bool EnableMultiSocketBinding { get; } = true;
/// <summary>
/// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network.
/// Depending on the address range implemented ULA ranges might not be used..
/// </summary>
public bool TrustAllIP6Interfaces { get; set; } = false;
/// <summary>
/// Gets or sets the ports that HDHomerun uses..
/// </summary>
public string HDHomerunPortRange { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the PublishedServerUriBySubnet
/// Gets or sets PublishedServerUri to advertise for specific subnets..
/// </summary>
public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>();
/// <summary>
/// Gets or sets a value indicating whether Autodiscovery tracing is enabled..
/// </summary>
public bool AutoDiscoveryTracing { get; set; } = false;
/// <summary>
/// Gets or sets a value indicating whether Autodiscovery is enabled..
/// </summary>
public bool AutoDiscovery { get; set; } = true;
/// <summary>
/// Gets or sets the filter for remote IP connectivity. Used in conjuntion with <seealso cref="IsRemoteIPFilterBlacklist"/>..
/// </summary>
public string[] RemoteIPFilter { get; set; } = Array.Empty<string>();
/// <summary>
/// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist..
/// </summary>
public bool IsRemoteIPFilterBlacklist { get; set; } = false;
/// <summary>
/// Gets or sets a value indicating whether to enable automatic port forwarding..
/// </summary>
public bool EnableUPnP { get; set; } = false;
/// <summary>
/// Gets or sets a value indicating whether access outside of the LAN is permitted..
/// </summary>
public bool EnableRemoteAccess { get; set; } = true;
/// <summary>
/// Gets or sets the subnets that are deemed to make up the LAN..
/// </summary>
public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>();
/// <summary>
/// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used..
/// </summary>
public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>();
/// <summary>
/// Gets or sets the known proxies.
/// </summary>
public string[] KnownProxies { get; set; } = Array.Empty<string>();
}
}

View File

@ -0,0 +1,21 @@
using Jellyfin.Networking.Configuration;
using MediaBrowser.Common.Configuration;
namespace Jellyfin.Networking.Configuration
{
/// <summary>
/// Defines the <see cref="NetworkConfigurationExtensions" />.
/// </summary>
public static class NetworkConfigurationExtensions
{
/// <summary>
/// Retrieves the network configuration.
/// </summary>
/// <param name="config">The <see cref="IConfigurationManager"/>.</param>
/// <returns>The <see cref="NetworkConfiguration"/>.</returns>
public static NetworkConfiguration GetNetworkConfiguration(this IConfigurationManager config)
{
return config.GetConfiguration<NetworkConfiguration>("network");
}
}
}

View File

@ -0,0 +1,27 @@
using System.Collections.Generic;
using MediaBrowser.Common.Configuration;
namespace Jellyfin.Networking.Configuration
{
/// <summary>
/// Defines the <see cref="NetworkConfigurationFactory" />.
/// </summary>
public class NetworkConfigurationFactory : IConfigurationFactory
{
/// <summary>
/// The GetConfigurations.
/// </summary>
/// <returns>The <see cref="IEnumerable{ConfigurationStore}"/>.</returns>
public IEnumerable<ConfigurationStore> GetConfigurations()
{
return new[]
{
new ConfigurationStore
{
Key = "network",
ConfigurationType = typeof(NetworkConfiguration)
}
};
}
}
}

View File

@ -6,9 +6,9 @@ using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
using Jellyfin.Networking.Configuration;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Net;
using MediaBrowser.Model.Configuration;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using NetworkCollection;
@ -24,7 +24,7 @@ namespace Jellyfin.Networking.Manager
/// <summary>
/// Contains the description of the interface along with its index.
/// </summary>
private readonly SortedList<string, int> _interfaceNames;
private readonly Dictionary<string, int> _interfaceNames;
/// <summary>
/// Threading lock for network interfaces.
@ -96,7 +96,7 @@ namespace Jellyfin.Networking.Manager
/// </summary>
/// <param name="configurationManager">IServerConfigurationManager instance.</param>
/// <param name="logger">Logger to use for messages.</param>
#pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in InitialiseLAN function. Compiler doesn't yet recognise this.
#pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in UpdateSettings function. Compiler doesn't yet recognise this.
public NetworkManager(IConfigurationManager configurationManager, ILogger<NetworkManager> logger)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
@ -104,15 +104,9 @@ namespace Jellyfin.Networking.Manager
_interfaceAddresses = new NetCollection(unique: false);
_macAddresses = new List<PhysicalAddress>();
_interfaceNames = new SortedList<string, int>();
_interfaceNames = new Dictionary<string, int>();
_publishedServerUrls = new Dictionary<IPNetAddress, string>();
UpdateSettings((ServerConfiguration)_configurationManager.CommonConfiguration);
if (!IsIP6Enabled && !IsIP4Enabled)
{
throw new ApplicationException("IPv4 and IPv6 cannot both be disabled.");
}
NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged;
NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
@ -182,7 +176,7 @@ namespace Jellyfin.Networking.Manager
lock (_intLock)
{
return _internalInterfaces.Where(i => i.Address.Equals(address) && (i.Tag < 0)).Any();
return _internalInterfaces.Where(i => i.Address.Equals(address) && i.Tag < 0).Any();
}
}
@ -212,20 +206,18 @@ namespace Jellyfin.Networking.Manager
/// <inheritdoc/>
public bool IsExcluded(EndPoint ip)
{
if (ip != null)
{
return _excludedSubnets.Contains(((IPEndPoint)ip).Address);
}
return false;
return ip != null && IsExcluded(((IPEndPoint)ip).Address);
}
/// <inheritdoc/>
public NetCollection CreateIPCollection(string[] values, bool bracketed = false)
{
NetCollection col = new NetCollection();
if (values != null)
if (values == null)
{
return col;
}
for (int a = 0; a < values.Length; a++)
{
string v = values[a].Trim();
@ -256,7 +248,6 @@ namespace Jellyfin.Networking.Manager
_logger.LogInformation("Ignoring LAN value {value}. Reason : {reason}", v, e.Message);
}
}
}
return col;
}
@ -305,13 +296,10 @@ namespace Jellyfin.Networking.Manager
/// <inheritdoc/>
public string GetBindInterface(string source, out int? port)
{
if (!string.IsNullOrEmpty(source))
{
if (IPHost.TryParse(source, out IPHost host))
if (!string.IsNullOrEmpty(source) && IPHost.TryParse(source, out IPHost host))
{
return GetBindInterface(host, out port);
}
}
return GetBindInterface(IPHost.None, out port);
}
@ -345,7 +333,6 @@ namespace Jellyfin.Networking.Manager
public string GetBindInterface(IPObject source, out int? port)
{
port = null;
bool isChromeCast = source == IPNetAddress.IP4Loopback;
// Do we have a source?
bool haveSource = !source.Address.Equals(IPAddress.None);
bool isExternal = false;
@ -354,7 +341,7 @@ namespace Jellyfin.Networking.Manager
{
if (!IsIP6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6)
{
_logger.LogWarning("IPv6 is disabled in JellyFin, but enabled in the OS. This may affect how the interface is selected.");
_logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
}
if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork)
@ -364,7 +351,7 @@ namespace Jellyfin.Networking.Manager
isExternal = !IsInLocalNetwork(source);
if (MatchesPublishedServerUrl(source, isExternal, isChromeCast, out string result, out port))
if (MatchesPublishedServerUrl(source, isExternal, out string result, out port))
{
_logger.LogInformation("{0}: Using BindAddress {1}:{2}", source, result, port);
return result;
@ -528,14 +515,9 @@ namespace Jellyfin.Networking.Manager
public bool IsExcludedInterface(IPAddress address)
{
lock (_intLock)
{
if (_bindExclusions.Count > 0)
{
return _bindExclusions.Contains(address);
}
return false;
}
}
/// <inheritdoc/>
@ -596,16 +578,20 @@ namespace Jellyfin.Networking.Manager
/// <summary>
/// Reloads all settings and re-initialises the instance.
/// </summary>
/// <param name="config"><seealso cref="ServerConfiguration"/> to use.</param>
public void UpdateSettings(ServerConfiguration config)
/// <param name="configuration">The configuration to use.</param>
public void UpdateSettings(object configuration)
{
if (config == null)
{
throw new ArgumentNullException(nameof(config));
}
NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration));
IsIP4Enabled = Socket.OSSupportsIPv6 && config.EnableIPV4;
IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6;
if (!IsIP6Enabled && !IsIP4Enabled)
{
_logger.LogError("IPv4 and IPv6 cannot both be disabled.");
IsIP4Enabled = true;
}
TrustAllIP6Interfaces = config.TrustAllIP6Interfaces;
UdpHelper.EnableMultiSocketBinding = config.EnableMultiSocketBinding;
@ -655,7 +641,7 @@ namespace Jellyfin.Networking.Manager
private void ConfigurationUpdated(object? sender, EventArgs args)
{
UpdateSettings((ServerConfiguration)_configurationManager.CommonConfiguration);
UpdateSettings(_configurationManager.GetNetworkConfiguration());
}
/// <summary>
@ -804,7 +790,7 @@ namespace Jellyfin.Networking.Manager
await Task.Delay(2000).ConfigureAwait(false);
InitialiseInterfaces();
// Recalculate LAN caches.
InitialiseLAN((ServerConfiguration)_configurationManager.CommonConfiguration);
InitialiseLAN(_configurationManager.GetNetworkConfiguration());
NetworkChanged?.Invoke(this, EventArgs.Empty);
}
@ -835,7 +821,7 @@ namespace Jellyfin.Networking.Manager
/// format is subnet=ipaddress|host|uri
/// when subnet = 0.0.0.0, any external address matches.
/// </summary>
private void InitialiseOverrides(ServerConfiguration config)
private void InitialiseOverrides(NetworkConfiguration config)
{
lock (_intLock)
{
@ -884,7 +870,7 @@ namespace Jellyfin.Networking.Manager
}
}
private void InitialiseBind(ServerConfiguration config)
private void InitialiseBind(NetworkConfiguration config)
{
string[] ba = config.LocalNetworkAddresses;
@ -912,7 +898,7 @@ namespace Jellyfin.Networking.Manager
_logger.LogInformation("Using bind exclusions: {0}", _bindExclusions);
}
private void InitialiseRemote(ServerConfiguration config)
private void InitialiseRemote(NetworkConfiguration config)
{
RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter);
}
@ -920,7 +906,7 @@ namespace Jellyfin.Networking.Manager
/// <summary>
/// Initialises internal LAN cache settings.
/// </summary>
private void InitialiseLAN(ServerConfiguration config)
private void InitialiseLAN(NetworkConfiguration config)
{
lock (_intLock)
{
@ -1029,8 +1015,7 @@ namespace Jellyfin.Networking.Manager
};
int tag = nw.Tag;
/* Mono on OSX doesn't give any gateway addresses, so check DNS entries */
if ((ipProperties.GatewayAddresses.Count > 0 || ipProperties.DnsAddresses.Count > 0) && !nw.IsLoopback())
if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback())
{
// -ve Tags signify the interface has a gateway.
nw.Tag *= -1;
@ -1051,8 +1036,7 @@ namespace Jellyfin.Networking.Manager
};
int tag = nw.Tag;
/* Mono on OSX doesn't give any gateway addresses, so check DNS entries */
if ((ipProperties.GatewayAddresses.Count > 0 || ipProperties.DnsAddresses.Count > 0) && !nw.IsLoopback())
if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback())
{
// -ve Tags signify the interface has a gateway.
nw.Tag *= -1;
@ -1112,11 +1096,10 @@ namespace Jellyfin.Networking.Manager
/// </summary>
/// <param name="source">IP source address to use.</param>
/// <param name="isExternal">True if the source is in the external subnet.</param>
/// <param name="isChromeCast">True if the request is for a chromecast device.</param>
/// <param name="bindPreference">The published server url that matches the source address.</param>
/// <param name="port">The resultant port, if one exists.</param>
/// <returns>True if a match is found.</returns>
private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, bool isChromeCast, out string bindPreference, out int? port)
private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, out string bindPreference, out int? port)
{
bindPreference = string.Empty;
port = null;
@ -1130,7 +1113,7 @@ namespace Jellyfin.Networking.Manager
bindPreference = addr.Value;
break;
}
else if ((addr.Key.Equals(IPAddress.Any) || addr.Key.Equals(IPAddress.IPv6Any)) && (isExternal || isChromeCast))
else if ((addr.Key.Equals(IPAddress.Any) || addr.Key.Equals(IPAddress.IPv6Any)) && isExternal)
{
// External.
bindPreference = addr.Value;
@ -1241,7 +1224,7 @@ namespace Jellyfin.Networking.Manager
}
/// <summary>
/// Attempts to match the source against am external interface.
/// Attempts to match the source against an external interface.
/// </summary>
/// <param name="source">IP source address to use.</param>
/// <param name="result">The result, if a match is found.</param>

View File

@ -3,7 +3,6 @@ using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using MediaBrowser.Model.Configuration;
using Microsoft.AspNetCore.Http;
using NetworkCollection;
@ -27,7 +26,7 @@ namespace MediaBrowser.Common.Net
/// <summary>
/// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
/// </summary>
public bool TrustAllIP6Interfaces { get; }
bool TrustAllIP6Interfaces { get; }
/// <summary>
/// Gets the remote address filter.
@ -37,12 +36,12 @@ namespace MediaBrowser.Common.Net
/// <summary>
/// Gets or sets a value indicating whether iP6 is enabled.
/// </summary>
public bool IsIP6Enabled { get; set; }
bool IsIP6Enabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether iP4 is enabled.
/// </summary>
public bool IsIP4Enabled { get; set; }
bool IsIP4Enabled { get; set; }
/// <summary>
/// Calculates the list of interfaces to use for Kestrel.
@ -57,7 +56,7 @@ namespace MediaBrowser.Common.Net
/// Returns a collection containing the loopback interfaces.
/// </summary>
/// <returns>Netcollection.</returns>
public NetCollection GetLoopbacks();
NetCollection GetLoopbacks();
/// <summary>
/// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo)
@ -93,7 +92,7 @@ namespace MediaBrowser.Common.Net
/// <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 above).
/// (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>
@ -103,7 +102,7 @@ namespace MediaBrowser.Common.Net
/// <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 above).
/// (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>
@ -113,7 +112,7 @@ namespace MediaBrowser.Common.Net
/// <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 above).
/// (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>
@ -138,7 +137,7 @@ namespace MediaBrowser.Common.Net
/// </summary>
/// <param name="addressObj">IP to check. Can be an IPAddress or an IPObject.</param>
/// <returns>Result of the check.</returns>
public bool IsGatewayInterface(object? addressObj);
bool IsGatewayInterface(object? addressObj);
/// <summary>
/// Returns true if the address is a private address.
@ -226,7 +225,7 @@ namespace MediaBrowser.Common.Net
/// <summary>
/// Reloads all settings and re-initialises the instance.
/// </summary>
/// <param name="config"><seealso cref="ServerConfiguration"/> to use.</param>
public void UpdateSettings(ServerConfiguration config);
/// <param name="configuration">The configuration to use.</param>
void UpdateSettings(object configuration);
}
}