diff options
| author | Bond-009 <bond.009@outlook.com> | 2023-11-14 21:10:41 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-11-14 21:10:41 +0100 |
| commit | 3ec2d5592ed296f444ae5e5dafd23985def13110 (patch) | |
| tree | 4423723a661e1f8656ce95edec1bd249fc46fe5a /MediaBrowser.Common | |
| parent | ea546230586a00a75db5c379db904e47cbbf270b (diff) | |
| parent | de0241e975c6b765f2af465734635a1a024a142a (diff) | |
Merge pull request #10574 from barronpm/dlna-plugin3
Move DLNA to Plugin (Part 1 (Part 2))
Diffstat (limited to 'MediaBrowser.Common')
| -rw-r--r-- | MediaBrowser.Common/Api/Policies.cs | 92 | ||||
| -rw-r--r-- | MediaBrowser.Common/Net/NetworkConfiguration.cs | 175 | ||||
| -rw-r--r-- | MediaBrowser.Common/Net/NetworkConfigurationExtensions.cs | 19 | ||||
| -rw-r--r-- | MediaBrowser.Common/Net/NetworkConfigurationFactory.cs | 22 | ||||
| -rw-r--r-- | MediaBrowser.Common/Net/NetworkConfigurationStore.cs | 23 | ||||
| -rw-r--r-- | MediaBrowser.Common/Net/NetworkConstants.cs | 75 | ||||
| -rw-r--r-- | MediaBrowser.Common/Net/NetworkUtils.cs | 345 |
7 files changed, 751 insertions, 0 deletions
diff --git a/MediaBrowser.Common/Api/Policies.cs b/MediaBrowser.Common/Api/Policies.cs new file mode 100644 index 000000000..e5427b8ef --- /dev/null +++ b/MediaBrowser.Common/Api/Policies.cs @@ -0,0 +1,92 @@ +namespace MediaBrowser.Common.Api; + +/// <summary> +/// Policies for the API authorization. +/// </summary> +public static class Policies +{ + /// <summary> + /// Policy name for requiring first time setup or elevated privileges. + /// </summary> + public const string FirstTimeSetupOrElevated = "FirstTimeSetupOrElevated"; + + /// <summary> + /// Policy name for requiring elevated privileges. + /// </summary> + public const string RequiresElevation = "RequiresElevation"; + + /// <summary> + /// Policy name for allowing local access only. + /// </summary> + public const string LocalAccessOnly = "LocalAccessOnly"; + + /// <summary> + /// Policy name for escaping schedule controls. + /// </summary> + public const string IgnoreParentalControl = "IgnoreParentalControl"; + + /// <summary> + /// Policy name for requiring download permission. + /// </summary> + public const string Download = "Download"; + + /// <summary> + /// Policy name for requiring first time setup or default permissions. + /// </summary> + public const string FirstTimeSetupOrDefault = "FirstTimeSetupOrDefault"; + + /// <summary> + /// Policy name for requiring local access or elevated privileges. + /// </summary> + public const string LocalAccessOrRequiresElevation = "LocalAccessOrRequiresElevation"; + + /// <summary> + /// Policy name for requiring (anonymous) LAN access. + /// </summary> + public const string AnonymousLanAccessPolicy = "AnonymousLanAccessPolicy"; + + /// <summary> + /// Policy name for escaping schedule controls or requiring first time setup. + /// </summary> + public const string FirstTimeSetupOrIgnoreParentalControl = "FirstTimeSetupOrIgnoreParentalControl"; + + /// <summary> + /// Policy name for accessing SyncPlay. + /// </summary> + public const string SyncPlayHasAccess = "SyncPlayHasAccess"; + + /// <summary> + /// Policy name for creating a SyncPlay group. + /// </summary> + public const string SyncPlayCreateGroup = "SyncPlayCreateGroup"; + + /// <summary> + /// Policy name for joining a SyncPlay group. + /// </summary> + public const string SyncPlayJoinGroup = "SyncPlayJoinGroup"; + + /// <summary> + /// Policy name for accessing a SyncPlay group. + /// </summary> + public const string SyncPlayIsInGroup = "SyncPlayIsInGroup"; + + /// <summary> + /// Policy name for accessing collection management. + /// </summary> + public const string CollectionManagement = "CollectionManagement"; + + /// <summary> + /// Policy name for accessing LiveTV. + /// </summary> + public const string LiveTvAccess = "LiveTvAccess"; + + /// <summary> + /// Policy name for managing LiveTV. + /// </summary> + public const string LiveTvManagement = "LiveTvManagement"; + + /// <summary> + /// Policy name for accessing subtitles management. + /// </summary> + public const string SubtitleManagement = "SubtitleManagement"; +} diff --git a/MediaBrowser.Common/Net/NetworkConfiguration.cs b/MediaBrowser.Common/Net/NetworkConfiguration.cs new file mode 100644 index 000000000..61a51c99e --- /dev/null +++ b/MediaBrowser.Common/Net/NetworkConfiguration.cs @@ -0,0 +1,175 @@ +#pragma warning disable CA1819 // Properties should not return arrays + +using System; + +namespace MediaBrowser.Common.Net; + +/// <summary> +/// Defines the <see cref="NetworkConfiguration" />. +/// </summary> +public class NetworkConfiguration +{ + /// <summary> + /// The default value for <see cref="InternalHttpPort"/>. + /// </summary> + public const int DefaultHttpPort = 8096; + + /// <summary> + /// The default value for <see cref="PublicHttpsPort"/> and <see cref="InternalHttpsPort"/>. + /// </summary> + public const int DefaultHttpsPort = 8920; + + private string _baseUrl = string.Empty; + + /// <summary> + /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at. + /// </summary> + public string BaseUrl + { + get => _baseUrl; + set + { + // Normalize the start of the string + if (string.IsNullOrWhiteSpace(value)) + { + // If baseUrl is empty, set an empty prefix string + _baseUrl = string.Empty; + return; + } + + if (value[0] != '/') + { + // If baseUrl was not configured with a leading slash, append one for consistency + value = "/" + value; + } + + // Normalize the end of the string + if (value[^1] == '/') + { + // If baseUrl was configured with a trailing slash, remove it for consistency + value = value.Remove(value.Length - 1); + } + + _baseUrl = value; + } + } + + /// <summary> + /// Gets or sets a value indicating whether to use HTTPS. + /// </summary> + /// <remarks> + /// In order for HTTPS to be used, in addition to setting this to true, valid values must also be + /// provided for <see cref="CertificatePath"/> and <see cref="CertificatePassword"/>. + /// </remarks> + public bool EnableHttps { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the server should force connections over HTTPS. + /// </summary> + public bool RequireHttps { get; set; } + + /// <summary> + /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. + /// </summary> + public string CertificatePath { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>. + /// </summary> + public string CertificatePassword { get; set; } = string.Empty; + + /// <summary> + /// Gets or sets the internal HTTP server port. + /// </summary> + /// <value>The HTTP server port.</value> + public int InternalHttpPort { get; set; } = DefaultHttpPort; + + /// <summary> + /// Gets or sets the internal HTTPS server port. + /// </summary> + /// <value>The HTTPS server port.</value> + public int InternalHttpsPort { get; set; } = DefaultHttpsPort; + + /// <summary> + /// Gets or sets the public HTTP port. + /// </summary> + /// <value>The public HTTP port.</value> + public int PublicHttpPort { get; set; } = DefaultHttpPort; + + /// <summary> + /// Gets or sets the public HTTPS port. + /// </summary> + /// <value>The public HTTPS port.</value> + public int PublicHttpsPort { get; set; } = DefaultHttpsPort; + + /// <summary> + /// Gets or sets a value indicating whether Autodiscovery is enabled. + /// </summary> + public bool AutoDiscovery { get; set; } = true; + + /// <summary> + /// Gets or sets a value indicating whether to enable automatic port forwarding. + /// </summary> + public bool EnableUPnP { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether IPv6 is enabled. + /// </summary> + public bool EnableIPv4 { get; set; } = true; + + /// <summary> + /// Gets or sets a value indicating whether IPv6 is enabled. + /// </summary> + public bool EnableIPv6 { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether access from outside of the LAN is permitted. + /// </summary> + public bool EnableRemoteAccess { get; set; } = true; + + /// <summary> + /// Gets or sets the subnets that are deemed to make up the LAN. + /// </summary> + public string[] LocalNetworkSubnets { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used. + /// </summary> + public string[] LocalNetworkAddresses { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets the known proxies. + /// </summary> + public string[] KnownProxies { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be ignored for the purposes of binding. + /// </summary> + public bool IgnoreVirtualInterfaces { get; set; } = true; + + /// <summary> + /// Gets or sets a value indicating the interface name prefixes that should be ignored. The list can be comma separated and values are case-insensitive. <seealso cref="IgnoreVirtualInterfaces"/>. + /// </summary> + public string[] VirtualInterfaceNames { get; set; } = new string[] { "veth" }; + + /// <summary> + /// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests. + /// </summary> + public bool EnablePublishedServerUriByRequest { get; set; } = false; + + /// <summary> + /// Gets or sets the PublishedServerUriBySubnet + /// Gets or sets PublishedServerUri to advertise for specific subnets. + /// </summary> + public string[] PublishedServerUriBySubnet { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets the filter for remote IP connectivity. Used in conjunction with <seealso cref="IsRemoteIPFilterBlacklist"/>. + /// </summary> + public string[] RemoteIPFilter { get; set; } = Array.Empty<string>(); + + /// <summary> + /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist. + /// </summary> + public bool IsRemoteIPFilterBlacklist { get; set; } +} diff --git a/MediaBrowser.Common/Net/NetworkConfigurationExtensions.cs b/MediaBrowser.Common/Net/NetworkConfigurationExtensions.cs new file mode 100644 index 000000000..9288964d2 --- /dev/null +++ b/MediaBrowser.Common/Net/NetworkConfigurationExtensions.cs @@ -0,0 +1,19 @@ +using MediaBrowser.Common.Configuration; + +namespace MediaBrowser.Common.Net; + +/// <summary> +/// Defines the <see cref="NetworkConfigurationExtensions" />. +/// </summary> +public static class NetworkConfigurationExtensions +{ + /// <summary> + /// Retrieves the network configuration. + /// </summary> + /// <param name="config">The <see cref="IConfigurationManager"/>.</param> + /// <returns>The <see cref="NetworkConfiguration"/>.</returns> + public static NetworkConfiguration GetNetworkConfiguration(this IConfigurationManager config) + { + return config.GetConfiguration<NetworkConfiguration>(NetworkConfigurationStore.StoreKey); + } +} diff --git a/MediaBrowser.Common/Net/NetworkConfigurationFactory.cs b/MediaBrowser.Common/Net/NetworkConfigurationFactory.cs new file mode 100644 index 000000000..9309834f4 --- /dev/null +++ b/MediaBrowser.Common/Net/NetworkConfigurationFactory.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; +using MediaBrowser.Common.Configuration; + +namespace MediaBrowser.Common.Net; + +/// <summary> +/// Defines the <see cref="NetworkConfigurationFactory" />. +/// </summary> +public class NetworkConfigurationFactory : IConfigurationFactory +{ + /// <summary> + /// The GetConfigurations. + /// </summary> + /// <returns>The <see cref="IEnumerable{ConfigurationStore}"/>.</returns> + public IEnumerable<ConfigurationStore> GetConfigurations() + { + return new[] + { + new NetworkConfigurationStore() + }; + } +} diff --git a/MediaBrowser.Common/Net/NetworkConfigurationStore.cs b/MediaBrowser.Common/Net/NetworkConfigurationStore.cs new file mode 100644 index 000000000..d2f518707 --- /dev/null +++ b/MediaBrowser.Common/Net/NetworkConfigurationStore.cs @@ -0,0 +1,23 @@ +using MediaBrowser.Common.Configuration; + +namespace MediaBrowser.Common.Net; + +/// <summary> +/// A configuration that stores network related settings. +/// </summary> +public class NetworkConfigurationStore : ConfigurationStore +{ + /// <summary> + /// The name of the configuration in the storage. + /// </summary> + public const string StoreKey = "network"; + + /// <summary> + /// Initializes a new instance of the <see cref="NetworkConfigurationStore"/> class. + /// </summary> + public NetworkConfigurationStore() + { + ConfigurationType = typeof(NetworkConfiguration); + Key = StoreKey; + } +} diff --git a/MediaBrowser.Common/Net/NetworkConstants.cs b/MediaBrowser.Common/Net/NetworkConstants.cs new file mode 100644 index 000000000..396bc8fb5 --- /dev/null +++ b/MediaBrowser.Common/Net/NetworkConstants.cs @@ -0,0 +1,75 @@ +using System.Net; +using Microsoft.AspNetCore.HttpOverrides; + +namespace MediaBrowser.Common.Net; + +/// <summary> +/// Networking constants. +/// </summary> +public static class NetworkConstants +{ + /// <summary> + /// IPv4 mask bytes. + /// </summary> + public const int IPv4MaskBytes = 4; + + /// <summary> + /// IPv6 mask bytes. + /// </summary> + public const int IPv6MaskBytes = 16; + + /// <summary> + /// Minimum IPv4 prefix size. + /// </summary> + public const int MinimumIPv4PrefixSize = 32; + + /// <summary> + /// Minimum IPv6 prefix size. + /// </summary> + public const int MinimumIPv6PrefixSize = 128; + + /// <summary> + /// Whole IPv4 address space. + /// </summary> + public static readonly IPNetwork IPv4Any = new IPNetwork(IPAddress.Any, 0); + + /// <summary> + /// Whole IPv6 address space. + /// </summary> + public static readonly IPNetwork IPv6Any = new IPNetwork(IPAddress.IPv6Any, 0); + + /// <summary> + /// IPv4 Loopback as defined in RFC 5735. + /// </summary> + public static readonly IPNetwork IPv4RFC5735Loopback = new IPNetwork(IPAddress.Loopback, 8); + + /// <summary> + /// IPv4 private class A as defined in RFC 1918. + /// </summary> + public static readonly IPNetwork IPv4RFC1918PrivateClassA = new IPNetwork(IPAddress.Parse("10.0.0.0"), 8); + + /// <summary> + /// IPv4 private class B as defined in RFC 1918. + /// </summary> + public static readonly IPNetwork IPv4RFC1918PrivateClassB = new IPNetwork(IPAddress.Parse("172.16.0.0"), 12); + + /// <summary> + /// IPv4 private class C as defined in RFC 1918. + /// </summary> + public static readonly IPNetwork IPv4RFC1918PrivateClassC = new IPNetwork(IPAddress.Parse("192.168.0.0"), 16); + + /// <summary> + /// IPv6 loopback as defined in RFC 4291. + /// </summary> + public static readonly IPNetwork IPv6RFC4291Loopback = new IPNetwork(IPAddress.IPv6Loopback, 128); + + /// <summary> + /// IPv6 site local as defined in RFC 4291. + /// </summary> + public static readonly IPNetwork IPv6RFC4291SiteLocal = new IPNetwork(IPAddress.Parse("fe80::"), 10); + + /// <summary> + /// IPv6 unique local as defined in RFC 4193. + /// </summary> + public static readonly IPNetwork IPv6RFC4193UniqueLocal = new IPNetwork(IPAddress.Parse("fc00::"), 7); +} diff --git a/MediaBrowser.Common/Net/NetworkUtils.cs b/MediaBrowser.Common/Net/NetworkUtils.cs new file mode 100644 index 000000000..f3bff7fa9 --- /dev/null +++ b/MediaBrowser.Common/Net/NetworkUtils.cs @@ -0,0 +1,345 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Sockets; +using System.Text.RegularExpressions; +using Jellyfin.Extensions; +using Microsoft.AspNetCore.HttpOverrides; + +namespace MediaBrowser.Common.Net; + +/// <summary> +/// Defines the <see cref="NetworkUtils" />. +/// </summary> +public static partial class NetworkUtils +{ + // 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 + [GeneratedRegex(@"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$", RegexOptions.IgnoreCase, "en-US")] + private static partial Regex FqdnGeneratedRegex(); + + /// <summary> + /// Returns true if the IPAddress contains an IP6 Local link address. + /// </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 + /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. + /// </remarks> + public static bool IsIPv6LinkLocal(IPAddress address) + { + ArgumentNullException.ThrowIfNull(address); + + if (address.IsIPv4MappedToIPv6) + { + address = address.MapToIPv4(); + } + + if (address.AddressFamily != AddressFamily.InterNetworkV6) + { + 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> + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// </summary> + /// <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) + { + uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? NetworkConstants.MinimumIPv4PrefixSize : NetworkConstants.MinimumIPv6PrefixSize) - cidr); + addr = ((addr & 0xff000000) >> 24) + | ((addr & 0x00ff0000) >> 8) + | ((addr & 0x0000ff00) << 8) + | ((addr & 0x000000ff) << 24); + return new IPAddress(addr); + } + + /// <summary> + /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. + /// </summary> + /// <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) + { + uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? NetworkConstants.MinimumIPv4PrefixSize : NetworkConstants.MinimumIPv6PrefixSize) - cidr); + addr = ((addr & 0xff000000) >> 24) + | ((addr & 0x00ff0000) >> 8) + | ((addr & 0x0000ff00) << 8) + | ((addr & 0x000000ff) << 24); + return new IPAddress(addr); + } + + /// <summary> + /// Convert a subnet mask to a CIDR. IPv4 only. + /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. + /// </summary> + /// <param name="mask">Subnet mask.</param> + /// <returns>Byte CIDR representing the mask.</returns> + public static byte MaskToCidr(IPAddress mask) + { + ArgumentNullException.ThrowIfNull(mask); + + byte cidrnet = 0; + if (mask.Equals(IPAddress.Any)) + { + return cidrnet; + } + + // GetAddressBytes + Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? NetworkConstants.IPv4MaskBytes : NetworkConstants.IPv6MaskBytes]; + if (!mask.TryWriteBytes(bytes, out var bytesWritten)) + { + Console.WriteLine("Unable to write address bytes, only ${bytesWritten} bytes written."); + } + + var zeroed = false; + for (var i = 0; i < bytes.Length; i++) + { + 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 cidrnet; + } + + /// <summary> + /// Converts an IPAddress into a string. + /// IPv6 addresses are returned in [ ], with their scope removed. + /// </summary> + /// <param name="address">Address to convert.</param> + /// <returns>URI safe conversion of the address.</returns> + public static string FormatIPString(IPAddress? address) + { + if (address is null) + { + return string.Empty; + } + + var str = address.ToString(); + if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + int i = str.IndexOf('%', StringComparison.Ordinal); + if (i != -1) + { + str = str.Substring(0, i); + } + + return $"[{str}]"; + } + + return str; + } + + /// <summary> + /// 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="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, [NotNullWhen(true)] out IReadOnlyList<IPNetwork>? result, bool negated = false) + { + if (values is null || values.Length == 0) + { + result = null; + return false; + } + + var tmpResult = new List<IPNetwork>(); + for (int a = 0; a < values.Length; a++) + { + if (TryParseToSubnet(values[a], out var innerResult, negated)) + { + tmpResult.Add(innerResult); + } + } + + result = tmpResult; + return tmpResult.Count > 0; + } + + /// <summary> + /// 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="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(ReadOnlySpan<char> value, [NotNullWhen(true)] out IPNetwork? result, bool negated = false) + { + var splitString = value.Trim().Split('/'); + if (splitString.MoveNext()) + { + var ipBlock = splitString.Current; + var address = IPAddress.None; + if (negated && ipBlock.StartsWith("!") && IPAddress.TryParse(ipBlock[1..], out var tmpAddress)) + { + address = tmpAddress; + } + else if (!negated && IPAddress.TryParse(ipBlock, out tmpAddress)) + { + address = tmpAddress; + } + + if (address != IPAddress.None) + { + if (splitString.MoveNext()) + { + var subnetBlock = splitString.Current; + if (int.TryParse(subnetBlock, out var netmask)) + { + result = new IPNetwork(address, netmask); + return true; + } + else if (IPAddress.TryParse(subnetBlock, out var netmaskAddress)) + { + result = new IPNetwork(address, NetworkUtils.MaskToCidr(netmaskAddress)); + return true; + } + } + else if (address.AddressFamily == AddressFamily.InterNetwork) + { + result = address.Equals(IPAddress.Any) ? NetworkConstants.IPv4Any : new IPNetwork(address, NetworkConstants.MinimumIPv4PrefixSize); + return true; + } + else if (address.AddressFamily == AddressFamily.InterNetworkV6) + { + result = address.Equals(IPAddress.IPv6Any) ? NetworkConstants.IPv6Any : new IPNetwork(address, NetworkConstants.MinimumIPv6PrefixSize); + return true; + } + } + } + + result = null; + return false; + } + + /// <summary> + /// Attempts to parse a host span. + /// </summary> + /// <param name="host">Host name to parse.</param> + /// <param name="addresses">Object representing the span, 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(ReadOnlySpan<char> host, [NotNullWhen(true)] out IPAddress[]? addresses, bool isIPv4Enabled = true, bool isIPv6Enabled = false) + { + host = host.Trim(); + if (host.IsEmpty) + { + addresses = null; + return false; + } + + // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. + if (host[0] == '[') + { + int i = host.IndexOf(']'); + if (i != -1) + { + return TryParseHost(host[1..(i - 1)], out addresses); + } + + addresses = Array.Empty<IPAddress>(); + return false; + } + + var hosts = new List<string>(); + foreach (var splitSpan in host.Split(':')) + { + hosts.Add(splitSpan.ToString()); + } + + if (hosts.Count <= 2) + { + var firstPart = hosts[0]; + + // Is hostname or hostname:port + if (FqdnGeneratedRegex().IsMatch(firstPart)) + { + try + { + // .NET automatically filters only supported returned addresses based on OS support. + addresses = Dns.GetHostAddresses(firstPart); + return true; + } + catch (SocketException) + { + // Ignore socket errors, as the result value will just be an empty array. + } + } + + // Is an IPv4 or IPv4:port + if (IPAddress.TryParse(firstPart.AsSpan().LeftPart('/'), out var address)) + { + 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 IPv4 address, so fake resolve. + return true; + } + } + else if (hosts.Count > 0 && hosts.Count <= 9) // 8 octets + port + { + if (IPAddress.TryParse(host.LeftPart('/'), out var address)) + { + addresses = new[] { address }; + return true; + } + } + + addresses = Array.Empty<IPAddress>(); + return false; + } + + /// <summary> + /// Gets the broadcast address for a <see cref="IPNetwork"/>. + /// </summary> + /// <param name="network">The <see cref="IPNetwork"/>.</param> + /// <returns>The broadcast address.</returns> + public static IPAddress GetBroadcastAddress(IPNetwork network) + { + var addressBytes = network.Prefix.GetAddressBytes(); + uint ipAddress = BitConverter.ToUInt32(addressBytes, 0); + uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressBytes(), 0); + uint broadCastIPAddress = ipAddress | ~ipMaskV4; + + return new IPAddress(BitConverter.GetBytes(broadCastIPAddress)); + } +} |
