aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Net/NetworkExtensions.cs
diff options
context:
space:
mode:
Diffstat (limited to 'MediaBrowser.Common/Net/NetworkExtensions.cs')
-rw-r--r--MediaBrowser.Common/Net/NetworkExtensions.cs391
1 files changed, 253 insertions, 138 deletions
diff --git a/MediaBrowser.Common/Net/NetworkExtensions.cs b/MediaBrowser.Common/Net/NetworkExtensions.cs
index 5e5e5b81b..97f0abbb5 100644
--- a/MediaBrowser.Common/Net/NetworkExtensions.cs
+++ b/MediaBrowser.Common/Net/NetworkExtensions.cs
@@ -1,6 +1,10 @@
using System;
-using System.Collections.ObjectModel;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
using System.Net;
+using System.Net.Sockets;
+using System.Text.RegularExpressions;
+using Microsoft.AspNetCore.HttpOverrides;
namespace MediaBrowser.Common.Net
{
@@ -9,240 +13,351 @@ namespace MediaBrowser.Common.Net
/// </summary>
public static class NetworkExtensions
{
+ // Use regular expression as CheckHostName isn't RFC5892 compliant.
+ // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-validation
+ private static readonly Regex _fqdnRegex = new Regex(@"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$");
+
/// <summary>
- /// Add an address to the collection.
+ /// Returns true if the IPAddress contains an IP6 Local link address.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="ip">Item to add.</param>
- public static void AddItem(this Collection<IPObject> source, IPAddress ip)
+ /// <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
+ /// it appears that the IPAddress.IsIPv6LinkLocal is out of date.
+ /// </remarks>
+ public static bool IsIPv6LinkLocal(IPAddress address)
{
- if (!source.ContainsAddress(ip))
+ ArgumentNullException.ThrowIfNull(address);
+
+ if (address.IsIPv4MappedToIPv6)
+ {
+ address = address.MapToIPv4();
+ }
+
+ if (address.AddressFamily != AddressFamily.InterNetworkV6)
{
- source.Add(new IPNetAddress(ip, 32));
+ return false;
}
+
+ // GetAddressBytes
+ Span<byte> octet = stackalloc byte[16];
+ address.TryWriteBytes(octet, out _);
+ uint word = (uint)(octet[0] << 8) + octet[1];
+
+ return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link.
}
/// <summary>
- /// Adds a network to the collection.
+ /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="item">Item to add.</param>
- /// <param name="itemsAreNetworks">If <c>true</c> the values are treated as subnets.
- /// If <b>false</b> items are addresses.</param>
- public static void AddItem(this Collection<IPObject> source, IPObject item, bool itemsAreNetworks = true)
+ /// <param name="cidr">Subnet mask in CIDR notation.</param>
+ /// <param name="family">IPv4 or IPv6 family.</param>
+ /// <returns>String value of the subnet mask in dotted decimal notation.</returns>
+ public static IPAddress CidrToMask(byte cidr, AddressFamily family)
{
- if (!source.ContainsAddress(item) || !itemsAreNetworks)
- {
- source.Add(item);
- }
+ uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? 32 : 128) - cidr);
+ addr = ((addr & 0xff000000) >> 24)
+ | ((addr & 0x00ff0000) >> 8)
+ | ((addr & 0x0000ff00) << 8)
+ | ((addr & 0x000000ff) << 24);
+ return new IPAddress(addr);
}
/// <summary>
- /// Converts this object to a string.
+ /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <returns>Returns a string representation of this object.</returns>
- public static string AsString(this Collection<IPObject> source)
+ /// <param name="cidr">Subnet mask in CIDR notation.</param>
+ /// <param name="family">IPv4 or IPv6 family.</param>
+ /// <returns>String value of the subnet mask in dotted decimal notation.</returns>
+ public static IPAddress CidrToMask(int cidr, AddressFamily family)
{
- return $"[{string.Join(',', source)}]";
+ uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? 32 : 128) - cidr);
+ addr = ((addr & 0xff000000) >> 24)
+ | ((addr & 0x00ff0000) >> 8)
+ | ((addr & 0x0000ff00) << 8)
+ | ((addr & 0x000000ff) << 24);
+ return new IPAddress(addr);
}
/// <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.
+ /// Convert a subnet mask to a CIDR. IPv4 only.
+ /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask.
/// </summary>
- /// <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 Collection<IPObject> source, IPAddress item)
+ /// <param name="mask">Subnet mask.</param>
+ /// <returns>Byte CIDR representing the mask.</returns>
+ public static byte MaskToCidr(IPAddress mask)
{
- if (source.Count == 0)
- {
- return false;
- }
-
- ArgumentNullException.ThrowIfNull(item);
+ ArgumentNullException.ThrowIfNull(mask);
- if (item.IsIPv4MappedToIPv6)
+ byte cidrnet = 0;
+ if (!mask.Equals(IPAddress.Any))
{
- item = item.MapToIPv4();
- }
+ // GetAddressBytes
+ Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
+ mask.TryWriteBytes(bytes, out _);
- foreach (var i in source)
- {
- if (i.Contains(item))
+ var zeroed = false;
+ for (var i = 0; i < bytes.Length; i++)
{
- return true;
+ for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1)
+ {
+ if (zeroed)
+ {
+ // Invalid netmask.
+ return (byte)~cidrnet;
+ }
+
+ if ((v & 0x80) == 0)
+ {
+ zeroed = true;
+ }
+ else
+ {
+ cidrnet++;
+ }
+ }
}
}
- return false;
+ return cidrnet;
}
/// <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.
+ /// Converts an IPAddress into a string.
+ /// Ipv6 addresses are returned in [ ], with their scope removed.
/// </summary>
- /// <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 Collection<IPObject> source, IPObject item)
+ /// <param name="address">Address to convert.</param>
+ /// <returns>URI safe conversion of the address.</returns>
+ public static string FormatIpString(IPAddress? address)
{
- if (source.Count == 0)
+ if (address is null)
{
- return false;
+ return string.Empty;
}
- ArgumentNullException.ThrowIfNull(item);
-
- foreach (var i in source)
+ var str = address.ToString();
+ if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
- if (i.Contains(item))
+ int i = str.IndexOf('%', StringComparison.Ordinal);
+ if (i != -1)
{
- return true;
+ str = str.Substring(0, i);
}
+
+ return $"[{str}]";
}
- return false;
+ return str;
}
/// <summary>
- /// Compares two Collection{IPObject} objects. The order is ignored.
+ /// Try parsing an array of strings into <see cref="IPNetwork"/> objects, respecting exclusions.
+ /// Elements without a subnet mask will be represented as <see cref="IPNetwork"/> with a single IP.
/// </summary>
- /// <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 Collection<IPObject> source, Collection<IPObject> dest)
+ /// <param name="values">Input string array to be parsed.</param>
+ /// <param name="result">Collection of <see cref="IPNetwork"/>.</param>
+ /// <param name="negated">Boolean signaling if negated or not negated values should be parsed.</param>
+ /// <returns><c>True</c> if parsing was successful.</returns>
+ public static bool TryParseToSubnets(string[] values, out List<IPNetwork> result, bool negated = false)
{
- if (dest is null || source.Count != dest.Count)
+ result = new List<IPNetwork>();
+
+ if (values is null || values.Length == 0)
{
return false;
}
- foreach (var sourceItem in source)
+ for (int a = 0; a < values.Length; a++)
{
- bool found = false;
- foreach (var destItem in dest)
+ string[] v = values[a].Trim().Split("/");
+
+ var address = IPAddress.None;
+ if (negated && v[0].StartsWith('!'))
{
- if (sourceItem.Equals(destItem))
- {
- found = true;
- break;
- }
+ _ = IPAddress.TryParse(v[0][1..], out address);
+ }
+ else if (!negated)
+ {
+ _ = IPAddress.TryParse(v[0][0..], out address);
}
- if (!found)
+ if (address != IPAddress.None && address is not null)
{
- return false;
+ if (v.Length > 1 && int.TryParse(v[1], out var netmask))
+ {
+ result.Add(new IPNetwork(address, netmask));
+ }
+ else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress))
+ {
+ result.Add(new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress)));
+ }
+ else if (address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ result.Add(new IPNetwork(address, 32));
+ }
+ else if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ result.Add(new IPNetwork(address, 128));
+ }
}
}
- return true;
+ if (result.Count > 0)
+ {
+ return true;
+ }
+
+ return false;
}
/// <summary>
- /// Returns a collection containing the subnets of this collection given.
+ /// Try parsing a string into an <see cref="IPNetwork"/>, respecting exclusions.
+ /// Inputs without a subnet mask will be represented as <see cref="IPNetwork"/> with a single IP.
/// </summary>
- /// <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)
+ /// <param name="value">Input string to be parsed.</param>
+ /// <param name="result">An <see cref="IPNetwork"/>.</param>
+ /// <param name="negated">Boolean signaling if negated or not negated values should be parsed.</param>
+ /// <returns><c>True</c> if parsing was successful.</returns>
+ public static bool TryParseToSubnet(string value, out IPNetwork result, bool negated = false)
{
- ArgumentNullException.ThrowIfNull(source);
+ result = new IPNetwork(IPAddress.None, 32);
+
+ if (string.IsNullOrEmpty(value))
+ {
+ return false;
+ }
- Collection<IPObject> res = new Collection<IPObject>();
+ string[] v = value.Trim().Split("/");
+
+ var address = IPAddress.None;
+ if (negated && v[0].StartsWith('!'))
+ {
+ _ = IPAddress.TryParse(v[0][1..], out address);
+ }
+ else if (!negated)
+ {
+ _ = IPAddress.TryParse(v[0][0..], out address);
+ }
- foreach (IPObject i in source)
+ if (address != IPAddress.None && address is not null)
{
- if (i is IPNetAddress nw)
+ if (v.Length > 1 && int.TryParse(v[1], out var netmask))
{
- // Add the subnet calculated from the interface address/mask.
- var na = nw.NetworkAddress;
- na.Tag = i.Tag;
- res.AddItem(na);
+ result = new IPNetwork(address, netmask);
}
- else if (i is IPHost ipHost)
+ else if (v.Length > 1 && IPAddress.TryParse(v[1], out var netmaskAddress))
{
- // Flatten out IPHost and add all its ip addresses.
- foreach (var addr in ipHost.GetAddresses())
- {
- IPNetAddress host = new IPNetAddress(addr)
- {
- Tag = i.Tag
- };
-
- res.AddItem(host);
- }
+ result = new IPNetwork(address, NetworkExtensions.MaskToCidr(netmaskAddress));
}
+ else if (address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ result = new IPNetwork(address, 32);
+ }
+ else if (address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ result = new IPNetwork(address, 128);
+ }
+ }
+
+ if (!result.Prefix.Equals(IPAddress.None))
+ {
+ return true;
}
- return res;
+ return false;
}
/// <summary>
- /// Excludes all the items from this list that are found in excludeList.
+ /// Attempts to parse a host string.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="excludeList">Items to exclude.</param>
- /// <param name="isNetwork">Collection is a network collection.</param>
- /// <returns>A new collection, with the items excluded.</returns>
- public static Collection<IPObject> Exclude(this Collection<IPObject> source, Collection<IPObject> excludeList, bool isNetwork)
+ /// <param name="host">Host name to parse.</param>
+ /// <param name="addresses">Object representing the string, if it has successfully been parsed.</param>
+ /// <param name="isIpv4Enabled"><c>true</c> if IPv4 is enabled.</param>
+ /// <param name="isIpv6Enabled"><c>true</c> if IPv6 is enabled.</param>
+ /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns>
+ public static bool TryParseHost(string host, [NotNullWhen(true)] out IPAddress[] addresses, bool isIpv4Enabled = true, bool isIpv6Enabled = false)
{
- if (source.Count == 0 || excludeList is null)
+ if (string.IsNullOrWhiteSpace(host))
{
- return new Collection<IPObject>(source);
+ addresses = Array.Empty<IPAddress>();
+ return false;
}
- Collection<IPObject> results = new Collection<IPObject>();
+ host = host.Trim();
- bool found;
- foreach (var outer in source)
+ // See if it's an IPv6 with port address e.g. [::1] or [::1]:120.
+ if (host[0] == '[')
{
- found = false;
+ int i = host.IndexOf(']', StringComparison.Ordinal);
+ if (i != -1)
+ {
+ return TryParseHost(host.Remove(i)[1..], out addresses);
+ }
+
+ addresses = Array.Empty<IPAddress>();
+ return false;
+ }
+
+ var hosts = host.Split(':');
- foreach (var inner in excludeList)
+ if (hosts.Length <= 2)
+ {
+ // Is hostname or hostname:port
+ if (_fqdnRegex.IsMatch(hosts[0]))
{
- if (outer.Equals(inner))
+ try
+ {
+ addresses = Dns.GetHostAddresses(hosts[0]);
+ return true;
+ }
+ catch (SocketException)
{
- found = true;
- break;
+ // Log and then ignore socket errors, as the result value will just be an empty array.
+ Console.WriteLine("GetHostAddresses failed.");
}
}
- if (!found)
+ // Is an IP4 or IP4:port
+ host = hosts[0].Split('/')[0];
+
+ if (IPAddress.TryParse(host, out var address))
{
- results.AddItem(outer, isNetwork);
+ if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIpv4Enabled && isIpv6Enabled)) ||
+ ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIpv4Enabled && !isIpv6Enabled)))
+ {
+ addresses = Array.Empty<IPAddress>();
+ return false;
+ }
+
+ addresses = new[] { address };
+
+ // Host name is an ip4 address, so fake resolve.
+ return true;
}
}
+ else if (hosts.Length <= 9 && IPAddress.TryParse(host.Split('/')[0], out var address)) // 8 octets + port
+ {
+ addresses = new[] { address };
+ return true;
+ }
- return results;
+ addresses = Array.Empty<IPAddress>();
+ return false;
}
/// <summary>
- /// Returns all items that co-exist in this object and target.
+ /// Gets the broadcast address for a <see cref="IPNetwork"/>.
/// </summary>
- /// <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 Collection<IPObject> ThatAreContainedInNetworks(this Collection<IPObject> source, Collection<IPObject> target)
+ /// <param name="network">The <see cref="IPNetwork"/>.</param>
+ /// <returns>The broadcast address.</returns>
+ public static IPAddress GetBroadcastAddress(IPNetwork network)
{
- if (source.Count == 0)
- {
- return new Collection<IPObject>();
- }
-
- ArgumentNullException.ThrowIfNull(target);
-
- Collection<IPObject> nc = new Collection<IPObject>();
-
- foreach (IPObject i in source)
- {
- if (target.ContainsAddress(i))
- {
- nc.AddItem(i);
- }
- }
+ uint ipAddress = BitConverter.ToUInt32(network.Prefix.GetAddressBytes(), 0);
+ uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0);
+ uint broadCastIpAddress = ipAddress | ~ipMaskV4;
- return nc;
+ return new IPAddress(BitConverter.GetBytes(broadCastIpAddress));
}
}
}