diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs new file mode 100644 index 0000000000..38f11153ab --- /dev/null +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -0,0 +1,223 @@ +#pragma warning disable CA1819 // Properties should not return arrays + +using System; +using MediaBrowser.Model.Configuration; + +namespace Jellyfin.Networking.Configuration +{ + /// + /// Defines the . + /// + public class NetworkConfiguration + { + private string _baseUrl = string.Empty; + + /// + /// Gets the default http port. + /// + public const int DefaultHttpPort = 8096; + + /// + /// Gets the default https port. + /// + public const int DefaultHttpsPort = 8920; + + /// + /// Gets or sets a value indicating whether the server should force connections over HTTPS. + /// + public bool RequireHttps { get; set; } = false; + + /// + /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at. + /// + 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; + } + } + + /// + /// Gets or sets the public HTTPS port. + /// + /// The public HTTPS port. + public int PublicHttpsPort { get; set; } = DefaultHttpsPort; + + /// + /// Gets or sets the HTTP server port number. + /// + /// The HTTP server port number. + public int HttpServerPortNumber { get; set; } = DefaultHttpPort; + + /// + /// Gets or sets the HTTPS server port number. + /// + /// The HTTPS server port number. + public int HttpsPortNumber { get; set; } = DefaultHttpsPort; + + /// + /// Gets or sets a value indicating whether to use HTTPS. + /// + /// + /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be + /// provided for and . + /// + public bool EnableHttps { get; set; } = false; + + /// + /// Gets or sets the public mapped port. + /// + /// The public mapped port. + public int PublicPort { get; set; } = DefaultHttpPort; + + /// + /// Gets or sets a value indicating whether the http port should be mapped as part of UPnP automatic port forwarding.. + /// + public bool UPnPCreateHttpPortMap { get; set; } = false; + + /// + /// Gets or sets the UDPPortRange + /// Gets or sets client udp port range.. + /// + public string UDPPortRange { get; set; } = string.Empty; + + /// + /// Gets or sets a value indicating whether gets or sets IPV6 capability.. + /// + public bool EnableIPV6 { get; set; } = false; + + /// + /// Gets or sets a value indicating whether gets or sets IPV4 capability.. + /// + public bool EnableIPV4 { get; set; } = true; + + /// + /// 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.. + /// + public bool EnableSSDPTracing { get; set; } = false; + + /// + /// 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.. + /// + public string SSDPTracingFilter { get; set; } = string.Empty; + + /// + /// Gets or sets the number of times SSDP UDP messages are sent.. + /// + public int UDPSendCount { get; set; } = 2; + + /// + /// Gets or sets the delay between each groups of SSDP messages (in ms).. + /// + public int UDPSendDelay { get; set; } = 100; + + /// + /// Gets or sets a value indicating whether address names that match should be Ignore for the purposes of binding.. + /// + public bool IgnoreVirtualInterfaces { get; set; } = true; + + /// + /// Gets or sets the VirtualInterfaceNames + /// Gets or sets a value indicating the interfaces that should be ignored. The list can be comma separated. .. + /// + public string VirtualInterfaceNames { get; set; } = "vEthernet*"; + + /// + /// Gets or sets the time (in seconds) between the pings of SSDP gateway monitor.. + /// + public int GatewayMonitorPeriod { get; set; } = 60; + + /// + /// Gets a value indicating whether multi-socket binding is available.. + /// + public bool EnableMultiSocketBinding { get; } = true; + + /// + /// Gets or sets a value indicating whether all IPv6 interfaces should be treated as on the internal network. + /// Depending on the address range implemented ULA ranges might not be used.. + /// + public bool TrustAllIP6Interfaces { get; set; } = false; + + /// + /// Gets or sets the ports that HDHomerun uses.. + /// + public string HDHomerunPortRange { get; set; } = string.Empty; + + /// + /// Gets or sets the PublishedServerUriBySubnet + /// Gets or sets PublishedServerUri to advertise for specific subnets.. + /// + public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty(); + + /// + /// Gets or sets a value indicating whether Autodiscovery tracing is enabled.. + /// + public bool AutoDiscoveryTracing { get; set; } = false; + + /// + /// Gets or sets a value indicating whether Autodiscovery is enabled.. + /// + public bool AutoDiscovery { get; set; } = true; + + /// + /// Gets or sets the filter for remote IP connectivity. Used in conjuntion with .. + /// + public string[] RemoteIPFilter { get; set; } = Array.Empty(); + + /// + /// Gets or sets a value indicating whether contains a blacklist or a whitelist. Default is a whitelist.. + /// + public bool IsRemoteIPFilterBlacklist { get; set; } = false; + + /// + /// Gets or sets a value indicating whether to enable automatic port forwarding.. + /// + public bool EnableUPnP { get; set; } = false; + + /// + /// Gets or sets a value indicating whether access outside of the LAN is permitted.. + /// + public bool EnableRemoteAccess { get; set; } = true; + + /// + /// Gets or sets the subnets that are deemed to make up the LAN.. + /// + public string[] LocalNetworkSubnets { get; set; } = Array.Empty(); + + /// + /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used.. + /// + public string[] LocalNetworkAddresses { get; set; } = Array.Empty(); + + /// + /// Gets or sets the known proxies. + /// + public string[] KnownProxies { get; set; } = Array.Empty(); + } +} diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs new file mode 100644 index 0000000000..e77b17ba92 --- /dev/null +++ b/Jellyfin.Networking/Configuration/NetworkConfigurationExtensions.cs @@ -0,0 +1,21 @@ +using Jellyfin.Networking.Configuration; +using MediaBrowser.Common.Configuration; + +namespace Jellyfin.Networking.Configuration +{ + /// + /// Defines the . + /// + public static class NetworkConfigurationExtensions + { + /// + /// Retrieves the network configuration. + /// + /// The . + /// The . + public static NetworkConfiguration GetNetworkConfiguration(this IConfigurationManager config) + { + return config.GetConfiguration("network"); + } + } +} diff --git a/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs b/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs new file mode 100644 index 0000000000..ac0485d871 --- /dev/null +++ b/Jellyfin.Networking/Configuration/NetworkConfigurationFactory.cs @@ -0,0 +1,27 @@ +using System.Collections.Generic; +using MediaBrowser.Common.Configuration; + +namespace Jellyfin.Networking.Configuration +{ + /// + /// Defines the . + /// + public class NetworkConfigurationFactory : IConfigurationFactory + { + /// + /// The GetConfigurations. + /// + /// The . + public IEnumerable GetConfigurations() + { + return new[] + { + new ConfigurationStore + { + Key = "network", + ConfigurationType = typeof(NetworkConfiguration) + } + }; + } + } +} diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 6f2970ef89..491fe824da 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -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 /// /// Contains the description of the interface along with its index. /// - private readonly SortedList _interfaceNames; + private readonly Dictionary _interfaceNames; /// /// Threading lock for network interfaces. @@ -96,7 +96,7 @@ namespace Jellyfin.Networking.Manager /// /// IServerConfigurationManager instance. /// Logger to use for messages. -#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 logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); @@ -104,15 +104,9 @@ namespace Jellyfin.Networking.Manager _interfaceAddresses = new NetCollection(unique: false); _macAddresses = new List(); - _interfaceNames = new SortedList(); + _interfaceNames = new Dictionary(); _publishedServerUrls = new Dictionary(); - 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,50 +206,47 @@ namespace Jellyfin.Networking.Manager /// public bool IsExcluded(EndPoint ip) { - if (ip != null) - { - return _excludedSubnets.Contains(((IPEndPoint)ip).Address); - } - - return false; + return ip != null && IsExcluded(((IPEndPoint)ip).Address); } /// public NetCollection CreateIPCollection(string[] values, bool bracketed = false) { NetCollection col = new NetCollection(); - if (values != null) + if (values == null) { - for (int a = 0; a < values.Length; a++) - { - string v = values[a].Trim(); + return col; + } - try + for (int a = 0; a < values.Length; a++) + { + string v = values[a].Trim(); + + try + { + if (v.StartsWith("[", StringComparison.OrdinalIgnoreCase) && v.EndsWith("]", StringComparison.OrdinalIgnoreCase)) { - if (v.StartsWith("[", StringComparison.OrdinalIgnoreCase) && v.EndsWith("]", StringComparison.OrdinalIgnoreCase)) + if (bracketed) { - if (bracketed) - { - AddToCollection(col, v.Remove(v.Length - 1).Substring(1)); - } + AddToCollection(col, v.Remove(v.Length - 1).Substring(1)); } - else if (v.StartsWith("!", StringComparison.OrdinalIgnoreCase)) - { - if (bracketed) - { - AddToCollection(col, v.Substring(1)); - } - } - else if (!bracketed) + } + else if (v.StartsWith("!", StringComparison.OrdinalIgnoreCase)) + { + if (bracketed) { - AddToCollection(col, v); + AddToCollection(col, v.Substring(1)); } } - catch (ArgumentException e) + else if (!bracketed) { - _logger.LogInformation("Ignoring LAN value {value}. Reason : {reason}", v, e.Message); + AddToCollection(col, v); } } + catch (ArgumentException e) + { + _logger.LogInformation("Ignoring LAN value {value}. Reason : {reason}", v, e.Message); + } } return col; @@ -305,12 +296,9 @@ namespace Jellyfin.Networking.Manager /// public string GetBindInterface(string source, out int? port) { - if (!string.IsNullOrEmpty(source)) + if (!string.IsNullOrEmpty(source) && IPHost.TryParse(source, out IPHost host)) { - if (IPHost.TryParse(source, out IPHost host)) - { - return GetBindInterface(host, out port); - } + 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; @@ -529,12 +516,7 @@ namespace Jellyfin.Networking.Manager { lock (_intLock) { - if (_bindExclusions.Count > 0) - { - return _bindExclusions.Contains(address); - } - - return false; + return _bindExclusions.Contains(address); } } @@ -596,16 +578,20 @@ namespace Jellyfin.Networking.Manager /// /// Reloads all settings and re-initialises the instance. /// - /// to use. - public void UpdateSettings(ServerConfiguration config) + /// The configuration to use. + 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()); } /// @@ -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. /// - 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 /// /// Initialises internal LAN cache settings. /// - 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 /// /// IP source address to use. /// True if the source is in the external subnet. - /// True if the request is for a chromecast device. /// The published server url that matches the source address. /// The resultant port, if one exists. /// True if a match is found. - 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 } /// - /// Attempts to match the source against am external interface. + /// Attempts to match the source against an external interface. /// /// IP source address to use. /// The result, if a match is found. diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index 8789cd9d81..f60f369d6a 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -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 /// /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. /// - public bool TrustAllIP6Interfaces { get; } + bool TrustAllIP6Interfaces { get; } /// /// Gets the remote address filter. @@ -37,12 +36,12 @@ namespace MediaBrowser.Common.Net /// /// Gets or sets a value indicating whether iP6 is enabled. /// - public bool IsIP6Enabled { get; set; } + bool IsIP6Enabled { get; set; } /// /// Gets or sets a value indicating whether iP4 is enabled. /// - public bool IsIP4Enabled { get; set; } + bool IsIP4Enabled { get; set; } /// /// Calculates the list of interfaces to use for Kestrel. @@ -57,7 +56,7 @@ namespace MediaBrowser.Common.Net /// Returns a collection containing the loopback interfaces. /// /// Netcollection. - public NetCollection GetLoopbacks(); + NetCollection GetLoopbacks(); /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) @@ -93,7 +92,7 @@ namespace MediaBrowser.Common.Net /// /// 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 . /// /// Source of the request. /// Optional port returned, if it's part of an override. @@ -103,7 +102,7 @@ namespace MediaBrowser.Common.Net /// /// 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 . /// /// IP address of the request. /// Optional port returned, if it's part of an override. @@ -113,7 +112,7 @@ namespace MediaBrowser.Common.Net /// /// 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 . /// /// Source of the request. /// Optional port returned, if it's part of an override. @@ -138,7 +137,7 @@ namespace MediaBrowser.Common.Net /// /// IP to check. Can be an IPAddress or an IPObject. /// Result of the check. - public bool IsGatewayInterface(object? addressObj); + bool IsGatewayInterface(object? addressObj); /// /// Returns true if the address is a private address. @@ -226,7 +225,7 @@ namespace MediaBrowser.Common.Net /// /// Reloads all settings and re-initialises the instance. /// - /// to use. - public void UpdateSettings(ServerConfiguration config); + /// The configuration to use. + void UpdateSettings(object configuration); } }