diff options
| author | Greenback <jimcartlidge@yahoo.co.uk> | 2020-11-16 19:37:38 +0000 |
|---|---|---|
| committer | Greenback <jimcartlidge@yahoo.co.uk> | 2020-11-16 19:37:38 +0000 |
| commit | 978aa38f3bd19a55ed4f3587bf5fd7d583c317f5 (patch) | |
| tree | 1df37b9e573fcd2788e48ee258361f378bbbc5fa | |
| parent | 979de240cb758acc7866095e6a50ed5ccc6f1d38 (diff) | |
Updated PR1 code.
| -rw-r--r-- | Jellyfin.Networking/Configuration/NetworkConfiguration.cs | 50 | ||||
| -rw-r--r-- | Jellyfin.Networking/Manager/NetworkManager.cs | 141 | ||||
| -rw-r--r-- | MediaBrowser.Common/Net/INetworkManager.cs | 38 | ||||
| -rw-r--r-- | MediaBrowser.Common/Net/IPHost.cs | 33 | ||||
| -rw-r--r-- | MediaBrowser.Common/Net/IPObject.cs | 56 | ||||
| -rw-r--r-- | MediaBrowser.Common/Net/NetworkExtensions.cs | 70 |
6 files changed, 188 insertions, 200 deletions
diff --git a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs index 301e43251..e710eb3c7 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -11,12 +11,12 @@ namespace Jellyfin.Networking.Configuration public class NetworkConfiguration { /// <summary> - /// Gets the default http port. + /// The default value for <see cref="HttpServerPortNumber"/>. /// </summary> public const int DefaultHttpPort = 8096; /// <summary> - /// Gets the default https port. + /// The default value for <see cref="PublicHttpsPort"/> and <see cref="HttpsPortNumber"/>. /// </summary> public const int DefaultHttpsPort = 8920; @@ -94,124 +94,124 @@ namespace Jellyfin.Networking.Configuration 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.. + /// 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; } /// <summary> /// Gets or sets the UDPPortRange - /// Gets or sets client udp port range.. + /// 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.. + /// Gets or sets a value indicating whether gets or sets IPV6 capability. /// </summary> public bool EnableIPV6 { get; set; } /// <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> 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.. + /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work. /// </summary> public bool EnableSSDPTracing { get; set; } /// <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.. + /// 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.. + /// 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).. + /// 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.. + /// 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"/>.. + /// 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.. + /// 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.. + /// 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.. + /// Depending on the address range implemented ULA ranges might not be used. /// </summary> public bool TrustAllIP6Interfaces { get; set; } /// <summary> - /// Gets or sets the ports that HDHomerun uses.. + /// 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.. + /// 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.. + /// Gets or sets a value indicating whether Autodiscovery tracing is enabled. /// </summary> public bool AutoDiscoveryTracing { get; set; } /// <summary> - /// Gets or sets a value indicating whether Autodiscovery is enabled.. + /// 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"/>.. + /// 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.. + /// 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; } /// <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> public bool EnableUPnP { get; set; } /// <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> public bool EnableRemoteAccess { get; set; } = true; /// <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> 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.. + /// 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>(); diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 289b1dc72..00711f162 100644 --- a/Jellyfin.Networking/Manager/NetworkManager.cs +++ b/Jellyfin.Networking/Manager/NetworkManager.cs @@ -1,7 +1,6 @@ -#pragma warning disable CA1021 // Avoid out parameters - using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Net; @@ -13,14 +12,12 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; -using NetCollection = System.Collections.ObjectModel.Collection<MediaBrowser.Common.Net.IPObject>; namespace Jellyfin.Networking.Manager { /// <summary> /// Class to take care of network interface management. - /// - /// Note: The normal collection methods and properties will not work with NetCollection. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>. + /// Note: The normal collection methods and properties will not work with Collection{IPObject}. <see cref="MediaBrowser.Common.Net.NetworkExtensions"/>. /// </summary> public class NetworkManager : INetworkManager, IDisposable { @@ -37,7 +34,7 @@ namespace Jellyfin.Networking.Manager /// <summary> /// List of all interface addresses and masks. /// </summary> - private readonly NetCollection _interfaceAddresses; + private readonly Collection<IPObject> _interfaceAddresses; /// <summary> /// List of all interface MAC addresses. @@ -61,30 +58,30 @@ namespace Jellyfin.Networking.Manager private bool _eventfire; /// <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. /// </summary> - private NetCollection _lanSubnets; + private Collection<IPObject> _lanSubnets; /// <summary> /// User defined list of subnets to excluded from the LAN. /// </summary> - private NetCollection _excludedSubnets; + private Collection<IPObject> _excludedSubnets; /// <summary> /// List of interface addresses to bind the WS. /// </summary> - private NetCollection _bindAddresses; + private Collection<IPObject> _bindAddresses; /// <summary> /// List of interface addresses to exclude from bind. /// </summary> - private NetCollection _bindExclusions; + private Collection<IPObject> _bindExclusions; /// <summary> /// Caches list of all internal filtered interface addresses and masks. /// </summary> - private NetCollection _internalInterfaces; + private Collection<IPObject> _internalInterfaces; /// <summary> /// 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)); _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager)); - _interfaceAddresses = new NetCollection(); + _interfaceAddresses = new Collection<IPObject>(); _macAddresses = new List<PhysicalAddress>(); _interfaceNames = new Dictionary<string, int>(); _publishedServerUrls = new Dictionary<IPNetAddress, string>(); @@ -143,7 +140,7 @@ namespace Jellyfin.Networking.Manager public bool IsIP4Enabled { get; set; } /// <inheritdoc/> - public NetCollection RemoteAddressFilter { get; private set; } + public Collection<IPObject> RemoteAddressFilter { get; private set; } /// <summary> /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. @@ -160,9 +157,9 @@ namespace Jellyfin.Networking.Manager /// </summary> /// <param name="source">Items to assign the collection, or null.</param> /// <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) { foreach (var item in source) @@ -189,22 +186,22 @@ namespace Jellyfin.Networking.Manager } /// <inheritdoc/> - public bool IsGatewayInterface(object? addressObj) + public bool IsGatewayInterface(IPObject? addressObj) { - var address = addressObj switch - { - IPAddress addressIp => addressIp, - IPObject addressIpObj => addressIpObj.Address, - _ => IPAddress.None - }; - + var address = addressObj?.Address ?? IPAddress.None; return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0); } /// <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) { nc.AddItem(IPAddress.Loopback); @@ -231,9 +228,9 @@ namespace Jellyfin.Networking.Manager } /// <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) { return col; @@ -256,7 +253,7 @@ namespace Jellyfin.Networking.Manager { if (bracketed) { - AddToCollection(col, v.Substring(1)); + AddToCollection(col, v[1..]); } } else if (!bracketed) @@ -266,7 +263,7 @@ namespace Jellyfin.Networking.Manager } 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/> - public NetCollection GetAllBindInterfaces(bool individualInterfaces = false) + public Collection<IPObject> GetAllBindInterfaces(bool individualInterfaces = false) { int count = _bindAddresses.Count; @@ -288,11 +285,11 @@ namespace Jellyfin.Networking.Manager if (individualInterfaces) { - return new NetCollection(_interfaceAddresses); + return new Collection<IPObject>(_interfaceAddresses); } // No bind address and no exclusions, so listen on all interfaces. - NetCollection result = new NetCollection(); + Collection<IPObject> result = new Collection<IPObject>(); if (IsIP4Enabled) { @@ -376,7 +373,7 @@ namespace Jellyfin.Networking.Manager 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; } } @@ -429,7 +426,7 @@ namespace Jellyfin.Networking.Manager } /// <inheritdoc/> - public NetCollection GetInternalBindAddresses() + public Collection<IPObject> GetInternalBindAddresses() { int count = _bindAddresses.Count; @@ -445,7 +442,7 @@ namespace Jellyfin.Networking.Manager return CreateCollection(_internalInterfaces.Where(p => !p.IsLoopback())); } - return new NetCollection(_bindAddresses); + return new Collection<IPObject>(_bindAddresses); } /// <inheritdoc/> @@ -526,7 +523,7 @@ namespace Jellyfin.Networking.Manager } /// <inheritdoc/> - public NetCollection GetFilteredLANSubnets(NetCollection? filter = null) + public Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null) { if (filter == null) { @@ -543,7 +540,7 @@ namespace Jellyfin.Networking.Manager } /// <inheritdoc/> - public bool TryParseInterface(string token, out NetCollection? result) + public bool TryParseInterface(string token, out Collection<IPObject>? result) { result = null; if (string.IsNullOrEmpty(token)) @@ -553,16 +550,16 @@ namespace Jellyfin.Networking.Manager 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); // Replace interface tags with the interface IP's. foreach (IPNetAddress iface in _interfaceAddresses) { - if (Math.Abs(iface.Tag) == index && - ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || - (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) + if (Math.Abs(iface.Tag) == index + && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) { result.AddItem(iface); } @@ -577,8 +574,8 @@ namespace Jellyfin.Networking.Manager /// <summary> /// Reloads all settings and re-initialises the instance. /// </summary> - /// <param name="configuration">The configuration to use.</param> - public void UpdateSettings(object configuration) + /// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param> + public void UpdateSettings(NetworkConfiguration configuration) { NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); @@ -622,7 +619,7 @@ namespace Jellyfin.Networking.Manager /// <summary> /// Protected implementation of Dispose pattern. /// </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) { if (!_disposed) @@ -639,11 +636,11 @@ namespace Jellyfin.Networking.Manager } /// <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> /// <param name="addr">String to parse.</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) { if (!string.IsNullOrEmpty(addr)) @@ -671,7 +668,7 @@ namespace Jellyfin.Networking.Manager /// Ipv6 addresses are returned in [ ], with their scope removed. /// </summary> /// <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) { var str = address.ToString(); @@ -694,7 +691,7 @@ namespace Jellyfin.Networking.Manager { if (evt.Key.Equals("network", StringComparison.Ordinal)) { - UpdateSettings(evt.NewConfiguration); + UpdateSettings((NetworkConfiguration)evt.NewConfiguration); } } @@ -703,7 +700,7 @@ namespace Jellyfin.Networking.Manager /// </summary> /// <param name="token">String to check.</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) { index = -1; @@ -720,8 +717,8 @@ namespace Jellyfin.Networking.Manager foreach ((string interfc, int interfcIndex) in _interfaceNames) { - if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) || - (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) + if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) + || (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture))) { index = interfcIndex; return true; @@ -733,11 +730,11 @@ namespace Jellyfin.Networking.Manager } /// <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> - /// <param name="col">Collection.</param> - /// <param name="token">String to parse.</param> - private void AddToCollection(NetCollection col, string token) + /// <param name="col"><see cref="Collection{IPObject}"/>Collection.</param> + /// <param name="token">String value to parse.</param> + private void AddToCollection(Collection<IPObject> col, string token) { // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1. // Null check required here for automated testing. @@ -748,9 +745,9 @@ namespace Jellyfin.Networking.Manager // Replace interface tags with the interface IP's. foreach (IPNetAddress iface in _interfaceAddresses) { - if (Math.Abs(iface.Tag) == index && - ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) || - (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) + if (Math.Abs(iface.Tag) == index + && ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) + || (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6))) { col.AddItem(iface); } @@ -791,7 +788,7 @@ namespace Jellyfin.Networking.Manager /// Handler for network change events. /// </summary> /// <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) { _logger.LogDebug("Network availability changed."); @@ -802,7 +799,7 @@ namespace Jellyfin.Networking.Manager /// Handler for network change events. /// </summary> /// <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) { _logger.LogDebug("Network address change detected."); @@ -812,7 +809,7 @@ namespace Jellyfin.Networking.Manager /// <summary> /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. /// </summary> - /// <returns>The network change async.</returns> + /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> private async Task OnNetworkChangeAsync() { try @@ -883,7 +880,7 @@ namespace Jellyfin.Networking.Manager { _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) { @@ -903,6 +900,9 @@ namespace Jellyfin.Networking.Manager } } + /// <summary> + /// Initialises the network bind addresses. + /// </summary> private void InitialiseBind(NetworkConfiguration config) { string[] lanAddresses = config.LocalNetworkAddresses; @@ -931,6 +931,9 @@ namespace Jellyfin.Networking.Manager _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString()); } + /// <summary> + /// Initialises the remote address values. + /// </summary> private void InitialiseRemote(NetworkConfiguration config) { RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter); @@ -964,7 +967,7 @@ namespace Jellyfin.Networking.Manager _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i))); // 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. 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="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> + /// <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) { bindPreference = string.Empty; @@ -1185,7 +1188,7 @@ namespace Jellyfin.Networking.Manager /// <param name="source">IP source address to use.</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> - /// <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) { 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. - NetCollection bindResult; + Collection<IPObject> bindResult; IPAddress? defaultGateway = null; IPAddress? bindAddress; @@ -1246,7 +1249,6 @@ namespace Jellyfin.Networking.Manager if (isExternal) { - // TODO: remove this after testing. _logger.LogWarning("{0}: External request received, however, only an internal interface bind found.", source); } @@ -1261,7 +1263,7 @@ namespace Jellyfin.Networking.Manager /// </summary> /// <param name="source">IP source address to use.</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) { result = string.Empty; @@ -1292,7 +1294,6 @@ namespace Jellyfin.Networking.Manager // 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); return false; } diff --git a/MediaBrowser.Common/Net/INetworkManager.cs b/MediaBrowser.Common/Net/INetworkManager.cs index a7beabbdc..43562afe3 100644 --- a/MediaBrowser.Common/Net/INetworkManager.cs +++ b/MediaBrowser.Common/Net/INetworkManager.cs @@ -1,10 +1,11 @@ #nullable enable using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Net; using System.Net.NetworkInformation; +using MediaBrowser.Common.Net; using Microsoft.AspNetCore.Http; -using NetCollection = System.Collections.ObjectModel.Collection<MediaBrowser.Common.Net.IPObject>; namespace MediaBrowser.Common.Net { @@ -31,7 +32,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Gets the remote address filter. /// </summary> - NetCollection RemoteAddressFilter { get; } + Collection<IPObject> RemoteAddressFilter { get; } /// <summary> /// Gets or sets a value indicating whether iP6 is enabled. @@ -46,17 +47,17 @@ namespace MediaBrowser.Common.Net /// <summary> /// Calculates the list of interfaces to use for Kestrel. /// </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 /// to represent any address.</returns> /// <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> /// Returns a collection containing the loopback interfaces. /// </summary> - /// <returns>Netcollection.</returns> - NetCollection GetLoopbacks(); + /// <returns>Collection{IPObject}.</returns> + Collection<IPObject> GetLoopbacks(); /// <summary> /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) @@ -137,7 +138,14 @@ 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> - 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> /// 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="result">Resultant object's ip addresses, if successful.</param> /// <returns>Success of the operation.</returns> - bool TryParseInterface(string token, out NetCollection? result); + bool TryParseInterface(string token, out Collection<IPObject>? result); /// <summary> - /// Parses an array of strings into a NetCollection. + /// Parses an array of strings into a Collection{IPObject}. /// </summary> /// <param name="values">Values to parse.</param> /// <param name="bracketed">When true, only include values in []. When false, ignore bracketed values.</param> /// <returns>IPCollection object containing the value strings.</returns> - NetCollection CreateIPCollection(string[] values, bool bracketed = false); + Collection<IPObject> CreateIPCollection(string[] values, bool bracketed = false); /// <summary> /// Returns all the internal Bind interface addresses. /// </summary> /// <returns>An internal list of interfaces addresses.</returns> - NetCollection GetInternalBindAddresses(); + Collection<IPObject> GetInternalBindAddresses(); /// <summary> /// Checks to see if an IP address is still a valid interface address. @@ -220,12 +228,6 @@ namespace MediaBrowser.Common.Net /// </summary> /// <param name="filter">Optional filter for the list.</param> /// <returns>Returns a filtered list of LAN addresses.</returns> - NetCollection GetFilteredLANSubnets(NetCollection? filter = null); - - /// <summary> - /// Reloads all settings and re-initialises the instance. - /// </summary> - /// <param name="configuration">The configuration to use.</param> - void UpdateSettings(object configuration); + Collection<IPObject> GetFilteredLANSubnets(Collection<IPObject>? filter = null); } } diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs index 80052727a..f9e1568ef 100644 --- a/MediaBrowser.Common/Net/IPHost.cs +++ b/MediaBrowser.Common/Net/IPHost.cs @@ -19,7 +19,7 @@ namespace MediaBrowser.Common.Net public static readonly IPHost None = new IPHost(string.Empty, IPAddress.None); /// <summary> - /// Time when last resolved. + /// Time when last resolved in ticks. /// </summary> private long _lastResolved; @@ -63,7 +63,8 @@ namespace MediaBrowser.Common.Net 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 { - return (byte)(ResolveHost() ? 128 : 0); + return (byte)(ResolveHost() ? 128 : 32); } 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> /// Gets a value indicating whether the address has a value. /// </summary> - public bool HasAddress - { - get - { - return _addresses.Length > 0; - } - } + public bool HasAddress => _addresses.Length != 0; /// <summary> /// Gets the host name of this object. @@ -128,7 +125,7 @@ namespace MediaBrowser.Common.Net /// </summary> /// <param name="host">Host name to parse.</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) { if (!string.IsNullOrEmpty(host)) @@ -142,7 +139,7 @@ namespace MediaBrowser.Common.Net else { // See if it's an IPv6 in [] with no port. - i = host.IndexOf("]", StringComparison.OrdinalIgnoreCase); + i = host.IndexOf(']', StringComparison.OrdinalIgnoreCase); if (i != -1) { return TryParse(host.Remove(i - 1).TrimStart(' ', '['), out hostObj); @@ -394,19 +391,19 @@ namespace MediaBrowser.Common.Net /// <summary> /// Attempt to resolve the ip address of a host. /// </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() { // When was the last time we resolved? if (_lastResolved == 0) { - _lastResolved = DateTime.Now.Ticks; + _lastResolved = DateTime.UtcNow.Ticks; } // 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(); Resolved = true; } @@ -417,7 +414,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Task that looks up a Host name and returns its IP addresses. /// </summary> - /// <returns>Array of IPAddress objects.</returns> + /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> private async Task ResolveHostInternal() { if (!string.IsNullOrEmpty(HostName)) diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs index 36f3357cc..d18ac9893 100644 --- a/MediaBrowser.Common/Net/IPObject.cs +++ b/MediaBrowser.Common/Net/IPObject.cs @@ -26,7 +26,7 @@ namespace MediaBrowser.Common.Net private IPObject? _networkAddress; /// <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> public int Tag { get; set; } @@ -38,18 +38,7 @@ namespace MediaBrowser.Common.Net /// <summary> /// Gets the object's network address. /// </summary> - public IPObject NetworkAddress - { - get - { - if (_networkAddress == null) - { - _networkAddress = CalculateNetworkAddress(); - } - - return _networkAddress; - } - } + public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress(); /// <summary> /// Gets or sets the object's IP address. @@ -92,22 +81,33 @@ namespace MediaBrowser.Common.Net 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(); int div = prefixLength / 8; int mod = prefixLength % 8; if (mod != 0) { + // Prefix length is counted right to left, so subtract 8 so we know how many bits to clear. mod = 8 - mod; + + // Shift out the bits from the octet that we don't want, by moving right then back left. addressBytes[div] = (byte)((int)addressBytes[div] >> mod << mod); + // Move on the next byte. div++; } + // Blank out the remaining octets from mod + 1 to the end of the byte array. (192.168.2.240/16 becomes 192.168.0.0) for (int octet = div; octet < addressBytes.Length; octet++) { addressBytes[octet] = 0; } + // Return the network address for the prefix. return (Address: new IPAddress(addressBytes), PrefixLength: prefixLength); } @@ -179,18 +179,18 @@ namespace MediaBrowser.Common.Net byte[] octet = address.GetAddressBytes(); - return (octet[0] == 10) || - (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) || // RFC1918 - (octet[0] == 192 && octet[1] == 168) || // RFC1918 - (octet[0] == 127); // RFC1122 + return (octet[0] == 10) + || (octet[0] == 172 && octet[1] >= 16 && octet[1] <= 31) // RFC1918 + || (octet[0] == 192 && octet[1] == 168) // RFC1918 + || (octet[0] == 127); // RFC1122 } else { byte[] octet = address.GetAddressBytes(); uint word = (uint)(octet[0] << 8) + octet[1]; - return (word >= 0xfe80 && word <= 0xfebf) || // fe80::/10 :Local link. - (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address. + return (word >= 0xfe80 && word <= 0xfebf) // fe80::/10 :Local link. + || (word >= 0xfc00 && word <= 0xfdff); // fc00::/7 :Unique local address. } } @@ -202,7 +202,8 @@ namespace MediaBrowser.Common.Net /// </summary> /// <param name="address">IPAddress object to check.</param> /// <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. /// </remarks> public static bool IsIPv6LinkLocal(IPAddress address) @@ -237,11 +238,10 @@ namespace MediaBrowser.Common.Net public static IPAddress CidrToMask(byte cidr, AddressFamily family) { uint addr = 0xFFFFFFFF << (family == AddressFamily.InterNetwork ? 32 : 128 - cidr); - addr = - ((addr & 0xff000000) >> 24) | - ((addr & 0x00ff0000) >> 8) | - ((addr & 0x0000ff00) << 8) | - ((addr & 0x000000ff) << 24); + addr = ((addr & 0xff000000) >> 24) + | ((addr & 0x00ff0000) >> 8) + | ((addr & 0x0000ff00) << 8) + | ((addr & 0x000000ff) << 24); return new IPAddress(addr); } @@ -304,7 +304,7 @@ namespace MediaBrowser.Common.Net /// <param name="family">Type of address to remove.</param> 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> @@ -352,9 +352,9 @@ namespace MediaBrowser.Common.Net /// <returns>Equality result.</returns> 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; diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs index e801de5eb..d07bba249 100644 --- a/MediaBrowser.Common/Net/NetworkExtensions.cs +++ b/MediaBrowser.Common/Net/NetworkExtensions.cs @@ -2,10 +2,10 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Net; using System.Runtime.CompilerServices; using System.Text; -using NetCollection = System.Collections.ObjectModel.Collection<MediaBrowser.Common.Net.IPObject>; namespace MediaBrowser.Common.Net { @@ -17,9 +17,9 @@ namespace MediaBrowser.Common.Net /// <summary> /// Add an address to the collection. /// </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> - public static void AddItem(this NetCollection source, IPAddress ip) + public static void AddItem(this Collection<IPObject> source, IPAddress ip) { if (!source.ContainsAddress(ip)) { @@ -30,9 +30,9 @@ namespace MediaBrowser.Common.Net /// <summary> /// Adds a network to the collection. /// </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> - public static void AddItem(this NetCollection source, IPObject item) + public static void AddItem(this Collection<IPObject> source, IPObject item) { if (!source.ContainsAddress(item)) { @@ -43,33 +43,21 @@ namespace MediaBrowser.Common.Net /// <summary> /// Converts this object to a string. /// </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> - public static string AsString(this NetCollection source) + public static string AsString(this Collection<IPObject> source) { - var sb = new StringBuilder(); - string output = "["; - if (source.Count > 0) - { - foreach (var i in source) - { - output += $"{i},"; - } - - output = output[0..^1]; - } - - return $"{output}]"; + return $"[{string.Join(',', source)}]"; } /// <summary> /// 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. /// </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> /// <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) { @@ -101,10 +89,10 @@ namespace MediaBrowser.Common.Net /// 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. /// </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> /// <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) { @@ -128,12 +116,12 @@ namespace MediaBrowser.Common.Net } /// <summary> - /// Compares two NetCollection objects. The order is ignored. + /// Compares two Collection{IPObject} objects. The order is ignored. /// </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> /// <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) { @@ -164,16 +152,16 @@ namespace MediaBrowser.Common.Net /// <summary> /// Returns a collection containing the subnets of this collection given. /// </summary> - /// <param name="source">The <see cref="NetCollection"/>.</param> - /// <returns>NetCollection object containing the subnets.</returns> - public static NetCollection AsNetworks(this NetCollection source) + /// <param name="source">The <see cref="Collection{IPObject}"/>.</param> + /// <returns>Collection{IPObject} object containing the subnets.</returns> + public static Collection<IPObject> AsNetworks(this Collection<IPObject> source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } - NetCollection res = new NetCollection(); + Collection<IPObject> res = new Collection<IPObject>(); foreach (IPObject i in source) { @@ -184,10 +172,10 @@ namespace MediaBrowser.Common.Net na.Tag = i.Tag; res.AddItem(na); } - else + else if (i is IPHost ipHost) { // 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) { @@ -205,17 +193,17 @@ namespace MediaBrowser.Common.Net /// <summary> /// Excludes all the items from this list that are found in excludeList. /// </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> /// <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) { - return new NetCollection(source); + return new Collection<IPObject>(source); } - NetCollection results = new NetCollection(); + Collection<IPObject> results = new Collection<IPObject>(); bool found; foreach (var outer in source) @@ -243,14 +231,14 @@ namespace MediaBrowser.Common.Net /// <summary> /// Returns all items that co-exist in this object and target. /// </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> /// <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) { - return new NetCollection(); + return new Collection<IPObject>(); } if (target == null) @@ -258,7 +246,7 @@ namespace MediaBrowser.Common.Net throw new ArgumentNullException(nameof(target)); } - NetCollection nc = new NetCollection(); + Collection<IPObject> nc = new Collection<IPObject>(); foreach (IPObject i in source) { |
