From 978aa38f3bd19a55ed4f3587bf5fd7d583c317f5 Mon Sep 17 00:00:00 2001 From: Greenback Date: Mon, 16 Nov 2020 19:37:38 +0000 Subject: Updated PR1 code. --- MediaBrowser.Common/Net/INetworkManager.cs | 38 ++++++++------- MediaBrowser.Common/Net/IPHost.cs | 33 ++++++------- MediaBrowser.Common/Net/IPObject.cs | 56 +++++++++++----------- MediaBrowser.Common/Net/NetworkExtensions.cs | 70 ++++++++++++---------------- 4 files changed, 92 insertions(+), 105 deletions(-) (limited to 'MediaBrowser.Common/Net') 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; 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 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); /// - /// 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 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; /// - /// 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 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; 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) { -- cgit v1.2.3