From 978aa38f3bd19a55ed4f3587bf5fd7d583c317f5 Mon Sep 17 00:00:00 2001 From: Greenback Date: Mon, 16 Nov 2020 19:37:38 +0000 Subject: [PATCH] Updated PR1 code. --- .../Configuration/NetworkConfiguration.cs | 50 +++---- Jellyfin.Networking/Manager/NetworkManager.cs | 141 +++++++++--------- MediaBrowser.Common/Net/INetworkManager.cs | 38 ++--- MediaBrowser.Common/Net/IPHost.cs | 33 ++-- MediaBrowser.Common/Net/IPObject.cs | 56 +++---- 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 301e432511..e710eb3c76 100644 --- a/Jellyfin.Networking/Configuration/NetworkConfiguration.cs +++ b/Jellyfin.Networking/Configuration/NetworkConfiguration.cs @@ -11,12 +11,12 @@ namespace Jellyfin.Networking.Configuration public class NetworkConfiguration { /// - /// Gets the default http port. + /// The default value for . /// public const int DefaultHttpPort = 8096; /// - /// Gets the default https port. + /// The default value for and . /// public const int DefaultHttpsPort = 8920; @@ -94,124 +94,124 @@ namespace Jellyfin.Networking.Configuration 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.. + /// 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; } /// /// Gets or sets the UDPPortRange - /// Gets or sets client udp port range.. + /// 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.. + /// Gets or sets a value indicating whether gets or sets IPV6 capability. /// public bool EnableIPV6 { get; set; } /// - /// Gets or sets a value indicating whether gets or sets IPV4 capability.. + /// 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.. + /// "Emby.Dlna": "Debug" must be set in logging.default.json for this property to work. /// public bool EnableSSDPTracing { get; set; } /// /// 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. /// public string SSDPTracingFilter { get; set; } = string.Empty; /// - /// Gets or sets the number of times SSDP UDP messages are sent.. + /// 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).. + /// 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.. + /// 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. .. + /// 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.. + /// 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.. + /// 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.. + /// Depending on the address range implemented ULA ranges might not be used. /// public bool TrustAllIP6Interfaces { get; set; } /// - /// Gets or sets the ports that HDHomerun uses.. + /// 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.. + /// 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.. + /// Gets or sets a value indicating whether Autodiscovery tracing is enabled. /// public bool AutoDiscoveryTracing { get; set; } /// - /// Gets or sets a value indicating whether Autodiscovery is enabled.. + /// 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 .. + /// 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.. + /// Gets or sets a value indicating whether contains a blacklist or a whitelist. Default is a whitelist. /// public bool IsRemoteIPFilterBlacklist { get; set; } /// - /// Gets or sets a value indicating whether to enable automatic port forwarding.. + /// Gets or sets a value indicating whether to enable automatic port forwarding. /// public bool EnableUPnP { get; set; } /// - /// 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. /// public bool EnableRemoteAccess { get; set; } = true; /// - /// 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. /// 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.. + /// 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(); diff --git a/Jellyfin.Networking/Manager/NetworkManager.cs b/Jellyfin.Networking/Manager/NetworkManager.cs index 289b1dc720..00711f1620 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; namespace Jellyfin.Networking.Manager { /// /// Class to take care of network interface management. - /// - /// Note: The normal collection methods and properties will not work with NetCollection. . + /// Note: The normal collection methods and properties will not work with Collection{IPObject}. . /// public class NetworkManager : INetworkManager, IDisposable { @@ -37,7 +34,7 @@ namespace Jellyfin.Networking.Manager /// /// List of all interface addresses and masks. /// - private readonly NetCollection _interfaceAddresses; + private readonly Collection _interfaceAddresses; /// /// List of all interface MAC addresses. @@ -61,30 +58,30 @@ namespace Jellyfin.Networking.Manager private bool _eventfire; /// - /// Unfiltered user defined LAN subnets. (Configuration.LocalNetworkSubnets). + /// Unfiltered user defined LAN subnets. () /// or internal interface network subnets if undefined by user. /// - private NetCollection _lanSubnets; + private Collection _lanSubnets; /// /// User defined list of subnets to excluded from the LAN. /// - private NetCollection _excludedSubnets; + private Collection _excludedSubnets; /// /// List of interface addresses to bind the WS. /// - private NetCollection _bindAddresses; + private Collection _bindAddresses; /// /// List of interface addresses to exclude from bind. /// - private NetCollection _bindExclusions; + private Collection _bindExclusions; /// /// Caches list of all internal filtered interface addresses and masks. /// - private NetCollection _internalInterfaces; + private Collection _internalInterfaces; /// /// 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(); _macAddresses = new List(); _interfaceNames = new Dictionary(); _publishedServerUrls = new Dictionary(); @@ -143,7 +140,7 @@ namespace Jellyfin.Networking.Manager public bool IsIP4Enabled { get; set; } /// - public NetCollection RemoteAddressFilter { get; private set; } + public Collection RemoteAddressFilter { get; private set; } /// /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. @@ -160,9 +157,9 @@ namespace Jellyfin.Networking.Manager /// /// Items to assign the collection, or null. /// The collection created. - public static NetCollection CreateCollection(IEnumerable? source = null) + public static Collection CreateCollection(IEnumerable? source = null) { - var result = new NetCollection(); + var result = new Collection(); if (source != null) { foreach (var item in source) @@ -189,22 +186,22 @@ namespace Jellyfin.Networking.Manager } /// - 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); } /// - 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); + } + + /// + public Collection GetLoopbacks() + { + Collection nc = new Collection(); if (IsIP4Enabled) { nc.AddItem(IPAddress.Loopback); @@ -231,9 +228,9 @@ namespace Jellyfin.Networking.Manager } /// - public NetCollection CreateIPCollection(string[] values, bool bracketed = false) + public Collection CreateIPCollection(string[] values, bool bracketed = false) { - NetCollection col = new NetCollection(); + Collection col = new Collection(); 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 } /// - public NetCollection GetAllBindInterfaces(bool individualInterfaces = false) + public Collection 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(_interfaceAddresses); } // No bind address and no exclusions, so listen on all interfaces. - NetCollection result = new NetCollection(); + Collection result = new Collection(); 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 } /// - public NetCollection GetInternalBindAddresses() + public Collection 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(_bindAddresses); } /// @@ -526,7 +523,7 @@ namespace Jellyfin.Networking.Manager } /// - public NetCollection GetFilteredLANSubnets(NetCollection? filter = null) + public Collection GetFilteredLANSubnets(Collection? filter = null) { if (filter == null) { @@ -543,7 +540,7 @@ namespace Jellyfin.Networking.Manager } /// - public bool TryParseInterface(string token, out NetCollection? result) + public bool TryParseInterface(string token, out Collection? 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(); _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 /// /// Reloads all settings and re-initialises the instance. /// - /// The configuration to use. - public void UpdateSettings(object configuration) + /// The to use. + public void UpdateSettings(NetworkConfiguration configuration) { NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration)); @@ -622,7 +619,7 @@ namespace Jellyfin.Networking.Manager /// /// Protected implementation of Dispose pattern. /// - /// True to dispose the managed state. + /// True to dispose the managed state. protected virtual void Dispose(bool disposing) { if (!_disposed) @@ -639,11 +636,11 @@ namespace Jellyfin.Networking.Manager } /// - /// Trys to identify the string and return an object of that class. + /// Tries to identify the string and return an object of that class. /// /// String to parse. /// IPObject to return. - /// True if the value parsed successfully. + /// true if the value parsed successfully, false otherwise. 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. /// /// Address to convert. - /// URI save conversion of the address. + /// URI safe conversion of the address. 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 /// /// String to check. /// Interface index number. - /// True if an interface name matches the token. + /// true if an interface name matches the token, False otherwise. 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 } /// - /// Parses strings into the collection, replacing any interface references. + /// Parses a string and adds it into the the collection, replacing any interface references. /// - /// Collection. - /// String to parse. - private void AddToCollection(NetCollection col, string token) + /// Collection. + /// String value to parse. + private void AddToCollection(Collection 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. /// /// Sender. - /// Network availability information. + /// A containing network availability information. 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. /// /// Sender. - /// Event arguments. + /// An . private void OnNetworkAddressChanged(object? sender, EventArgs e) { _logger.LogDebug("Network address change detected."); @@ -812,7 +809,7 @@ namespace Jellyfin.Networking.Manager /// /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession. /// - /// The network change async. + /// A representing the asynchronous operation. 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? addresses) && addresses != null) { foreach (IPNetAddress na in addresses) { @@ -903,6 +900,9 @@ namespace Jellyfin.Networking.Manager } } + /// + /// Initialises the network bind addresses. + /// 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()); } + /// + /// Initialises the remote address values. + /// 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(); // We must listen on loopback for LiveTV to function regardless of the settings. if (IsIP6Enabled) @@ -1131,7 +1134,7 @@ namespace Jellyfin.Networking.Manager /// True if the source is in the external subnet. /// The published server url that matches the source address. /// The resultant port, if one exists. - /// True if a match is found. + /// true if a match is found, false otherwise. private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, out string bindPreference, out int? port) { bindPreference = string.Empty; @@ -1185,7 +1188,7 @@ namespace Jellyfin.Networking.Manager /// IP source address to use. /// True if the source is in the external subnet. /// The result, if a match is found. - /// True if a match is found. + /// true if a match is found, false otherwise. 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 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 /// /// IP source address to use. /// The result, if a match is found. - /// True if a match is found. + /// true if a match is found, false otherwise. 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 a7beabbdcb..43562afe38 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; namespace MediaBrowser.Common.Net { @@ -31,7 +32,7 @@ namespace MediaBrowser.Common.Net /// /// Gets the remote address filter. /// - NetCollection RemoteAddressFilter { get; } + Collection RemoteAddressFilter { get; } /// /// Gets or sets a value indicating whether iP6 is enabled. @@ -46,17 +47,17 @@ namespace MediaBrowser.Common.Net /// /// Calculates the list of interfaces to use for Kestrel. /// - /// A NetCollection object containing all the interfaces to bind. + /// 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. /// When false, return or for all interfaces. - NetCollection GetAllBindInterfaces(bool individualInterfaces = false); + Collection GetAllBindInterfaces(bool individualInterfaces = false); /// /// Returns a collection containing the loopback interfaces. /// - /// Netcollection. - NetCollection GetLoopbacks(); + /// Collection{IPObject}. + Collection GetLoopbacks(); /// /// Retrieves the bind address to use in system url's. (Server Discovery, PlayTo, LiveTV, SystemInfo) @@ -137,7 +138,14 @@ namespace MediaBrowser.Common.Net /// /// IP to check. Can be an IPAddress or an IPObject. /// Result of the check. - bool IsGatewayInterface(object? addressObj); + bool IsGatewayInterface(IPObject? addressObj); + + /// + /// Checks to see if the IP Address provided matches an interface that has a gateway. + /// + /// IP to check. Can be an IPAddress or an IPObject. + /// Result of the check. + bool IsGatewayInterface(IPAddress? addressObj); /// /// Returns true if the address is a private address. @@ -178,21 +186,21 @@ namespace MediaBrowser.Common.Net /// Token to parse. /// Resultant object's ip addresses, if successful. /// Success of the operation. - bool TryParseInterface(string token, out NetCollection? result); + bool TryParseInterface(string token, out Collection? result); /// - /// Parses an array of strings into a NetCollection. + /// Parses an array of strings into a Collection{IPObject}. /// /// Values to parse. /// When true, only include values in []. When false, ignore bracketed values. /// IPCollection object containing the value strings. - NetCollection CreateIPCollection(string[] values, bool bracketed = false); + Collection CreateIPCollection(string[] values, bool bracketed = false); /// /// Returns all the internal Bind interface addresses. /// /// An internal list of interfaces addresses. - NetCollection GetInternalBindAddresses(); + Collection GetInternalBindAddresses(); /// /// Checks to see if an IP address is still a valid interface address. @@ -220,12 +228,6 @@ namespace MediaBrowser.Common.Net /// /// Optional filter for the list. /// Returns a filtered list of LAN addresses. - NetCollection GetFilteredLANSubnets(NetCollection? filter = null); - - /// - /// Reloads all settings and re-initialises the instance. - /// - /// The configuration to use. - void UpdateSettings(object configuration); + Collection GetFilteredLANSubnets(Collection? filter = null); } } diff --git a/MediaBrowser.Common/Net/IPHost.cs b/MediaBrowser.Common/Net/IPHost.cs index 80052727af..f9e1568efc 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); /// - /// Time when last resolved. + /// Time when last resolved in ticks. /// 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 /// /// Gets a value indicating whether the address has a value. /// - public bool HasAddress - { - get - { - return _addresses.Length > 0; - } - } + public bool HasAddress => _addresses.Length != 0; /// /// Gets the host name of this object. @@ -128,7 +125,7 @@ namespace MediaBrowser.Common.Net /// /// Host name to parse. /// Object representing the string, if it has successfully been parsed. - /// Success result of the parsing. + /// true if the parsing is successful, false if not. 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 /// /// Attempt to resolve the ip address of a host. /// - /// The result of the comparison function. + /// true if any addresses have been resolved, otherwise false. 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 /// /// Task that looks up a Host name and returns its IP addresses. /// - /// Array of IPAddress objects. + /// A representing the asynchronous operation. private async Task ResolveHostInternal() { if (!string.IsNullOrEmpty(HostName)) diff --git a/MediaBrowser.Common/Net/IPObject.cs b/MediaBrowser.Common/Net/IPObject.cs index 36f3357cce..d18ac98933 100644 --- a/MediaBrowser.Common/Net/IPObject.cs +++ b/MediaBrowser.Common/Net/IPObject.cs @@ -26,7 +26,7 @@ namespace MediaBrowser.Common.Net private IPObject? _networkAddress; /// - /// 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. /// public int Tag { get; set; } @@ -38,18 +38,7 @@ namespace MediaBrowser.Common.Net /// /// Gets the object's network address. /// - public IPObject NetworkAddress - { - get - { - if (_networkAddress == null) - { - _networkAddress = CalculateNetworkAddress(); - } - - return _networkAddress; - } - } + public IPObject NetworkAddress => _networkAddress ??= CalculateNetworkAddress(); /// /// 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 /// /// IPAddress object to check. /// True if it is a local link address. - /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress + /// + /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. /// 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 /// Type of address to remove. 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. } /// @@ -352,9 +352,9 @@ namespace MediaBrowser.Common.Net /// Equality result. 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 e801de5eb8..d07bba249b 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; namespace MediaBrowser.Common.Net { @@ -17,9 +17,9 @@ namespace MediaBrowser.Common.Net /// /// Add an address to the collection. /// - /// The . + /// The . /// Item to add. - public static void AddItem(this NetCollection source, IPAddress ip) + public static void AddItem(this Collection source, IPAddress ip) { if (!source.ContainsAddress(ip)) { @@ -30,9 +30,9 @@ namespace MediaBrowser.Common.Net /// /// Adds a network to the collection. /// - /// The . + /// The . /// Item to add. - public static void AddItem(this NetCollection source, IPObject item) + public static void AddItem(this Collection source, IPObject item) { if (!source.ContainsAddress(item)) { @@ -43,33 +43,21 @@ namespace MediaBrowser.Common.Net /// /// Converts this object to a string. /// - /// The . + /// The . /// Returns a string representation of this object. - public static string AsString(this NetCollection source) + public static string AsString(this Collection 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)}]"; } /// /// 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. /// - /// The . + /// The . /// The item to look for. /// True if the collection contains the item. - public static bool ContainsAddress(this NetCollection source, IPAddress item) + public static bool ContainsAddress(this Collection 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. /// - /// The . + /// The . /// The item to look for. /// True if the collection contains the item. - public static bool ContainsAddress(this NetCollection source, IPObject item) + public static bool ContainsAddress(this Collection source, IPObject item) { if (source.Count == 0) { @@ -128,12 +116,12 @@ namespace MediaBrowser.Common.Net } /// - /// Compares two NetCollection objects. The order is ignored. + /// Compares two Collection{IPObject} objects. The order is ignored. /// - /// The . + /// The . /// Item to compare to. /// True if both are equal. - public static bool Compare(this NetCollection source, NetCollection dest) + public static bool Compare(this Collection source, Collection dest) { if (dest == null || source.Count != dest.Count) { @@ -164,16 +152,16 @@ namespace MediaBrowser.Common.Net /// /// Returns a collection containing the subnets of this collection given. /// - /// The . - /// NetCollection object containing the subnets. - public static NetCollection AsNetworks(this NetCollection source) + /// The . + /// Collection{IPObject} object containing the subnets. + public static Collection AsNetworks(this Collection source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } - NetCollection res = new NetCollection(); + Collection res = new Collection(); 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 /// /// Excludes all the items from this list that are found in excludeList. /// - /// The . + /// The . /// Items to exclude. /// A new collection, with the items excluded. - public static NetCollection Exclude(this NetCollection source, NetCollection excludeList) + public static Collection Exclude(this Collection source, Collection excludeList) { if (source.Count == 0 || excludeList == null) { - return new NetCollection(source); + return new Collection(source); } - NetCollection results = new NetCollection(); + Collection results = new Collection(); bool found; foreach (var outer in source) @@ -243,14 +231,14 @@ namespace MediaBrowser.Common.Net /// /// Returns all items that co-exist in this object and target. /// - /// The . + /// The . /// Collection to compare with. /// A collection containing all the matches. - public static NetCollection Union(this NetCollection source, NetCollection target) + public static Collection Union(this Collection source, Collection target) { if (source.Count == 0) { - return new NetCollection(); + return new Collection(); } if (target == null) @@ -258,7 +246,7 @@ namespace MediaBrowser.Common.Net throw new ArgumentNullException(nameof(target)); } - NetCollection nc = new NetCollection(); + Collection nc = new Collection(); foreach (IPObject i in source) {