Updated PR1 code.

This commit is contained in:
Greenback
2020-11-16 19:37:38 +00:00
parent 979de240cb
commit 978aa38f3b
6 changed files with 188 additions and 200 deletions

View File

@@ -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);
}
}

View File

@@ -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))

View File

@@ -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;

View File

@@ -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)
{