| | 1 | | using System; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using System.Diagnostics.CodeAnalysis; |
| | 4 | | using System.Net; |
| | 5 | | using System.Net.Sockets; |
| | 6 | | using System.Text.RegularExpressions; |
| | 7 | | using Jellyfin.Extensions; |
| | 8 | | using IPNetwork = Microsoft.AspNetCore.HttpOverrides.IPNetwork; |
| | 9 | |
|
| | 10 | | namespace MediaBrowser.Common.Net; |
| | 11 | |
|
| | 12 | | /// <summary> |
| | 13 | | /// Defines the <see cref="NetworkUtils" />. |
| | 14 | | /// </summary> |
| | 15 | | public static partial class NetworkUtils |
| | 16 | | { |
| | 17 | | // Use regular expression as CheckHostName isn't RFC5892 compliant. |
| | 18 | | // Modified from gSkinner's expression at https://stackoverflow.com/questions/11809631/fully-qualified-domain-name-v |
| | 19 | | [GeneratedRegex(@"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$", Regex |
| | 20 | | private static partial Regex FqdnGeneratedRegex(); |
| | 21 | |
|
| | 22 | | /// <summary> |
| | 23 | | /// Returns true if the IPAddress contains an IP6 Local link address. |
| | 24 | | /// </summary> |
| | 25 | | /// <param name="address">IPAddress object to check.</param> |
| | 26 | | /// <returns>True if it is a local link address.</returns> |
| | 27 | | /// <remarks> |
| | 28 | | /// See https://stackoverflow.com/questions/6459928/explain-the-instance-properties-of-system-net-ipaddress |
| | 29 | | /// it appears that the IPAddress.IsIPv6LinkLocal is out of date. |
| | 30 | | /// </remarks> |
| | 31 | | public static bool IsIPv6LinkLocal(IPAddress address) |
| | 32 | | { |
| 0 | 33 | | ArgumentNullException.ThrowIfNull(address); |
| | 34 | |
|
| 0 | 35 | | if (address.IsIPv4MappedToIPv6) |
| | 36 | | { |
| 0 | 37 | | address = address.MapToIPv4(); |
| | 38 | | } |
| | 39 | |
|
| 0 | 40 | | if (address.AddressFamily != AddressFamily.InterNetworkV6) |
| | 41 | | { |
| 0 | 42 | | return false; |
| | 43 | | } |
| | 44 | |
|
| | 45 | | // GetAddressBytes |
| 0 | 46 | | Span<byte> octet = stackalloc byte[16]; |
| 0 | 47 | | address.TryWriteBytes(octet, out _); |
| 0 | 48 | | uint word = (uint)(octet[0] << 8) + octet[1]; |
| | 49 | |
|
| 0 | 50 | | return word >= 0xfe80 && word <= 0xfebf; // fe80::/10 :Local link. |
| | 51 | | } |
| | 52 | |
|
| | 53 | | /// <summary> |
| | 54 | | /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. |
| | 55 | | /// </summary> |
| | 56 | | /// <param name="cidr">Subnet mask in CIDR notation.</param> |
| | 57 | | /// <param name="family">IPv4 or IPv6 family.</param> |
| | 58 | | /// <returns>String value of the subnet mask in dotted decimal notation.</returns> |
| | 59 | | public static IPAddress CidrToMask(byte cidr, AddressFamily family) |
| | 60 | | { |
| 0 | 61 | | uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? NetworkConstants.MinimumIPv4PrefixSize : Netw |
| 0 | 62 | | addr = ((addr & 0xff000000) >> 24) |
| 0 | 63 | | | ((addr & 0x00ff0000) >> 8) |
| 0 | 64 | | | ((addr & 0x0000ff00) << 8) |
| 0 | 65 | | | ((addr & 0x000000ff) << 24); |
| 0 | 66 | | return new IPAddress(addr); |
| | 67 | | } |
| | 68 | |
|
| | 69 | | /// <summary> |
| | 70 | | /// Convert a subnet mask in CIDR notation to a dotted decimal string value. IPv4 only. |
| | 71 | | /// </summary> |
| | 72 | | /// <param name="cidr">Subnet mask in CIDR notation.</param> |
| | 73 | | /// <param name="family">IPv4 or IPv6 family.</param> |
| | 74 | | /// <returns>String value of the subnet mask in dotted decimal notation.</returns> |
| | 75 | | public static IPAddress CidrToMask(int cidr, AddressFamily family) |
| | 76 | | { |
| 0 | 77 | | uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? NetworkConstants.MinimumIPv4PrefixSize : Netw |
| 0 | 78 | | addr = ((addr & 0xff000000) >> 24) |
| 0 | 79 | | | ((addr & 0x00ff0000) >> 8) |
| 0 | 80 | | | ((addr & 0x0000ff00) << 8) |
| 0 | 81 | | | ((addr & 0x000000ff) << 24); |
| 0 | 82 | | return new IPAddress(addr); |
| | 83 | | } |
| | 84 | |
|
| | 85 | | /// <summary> |
| | 86 | | /// Convert a subnet mask to a CIDR. IPv4 only. |
| | 87 | | /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask. |
| | 88 | | /// </summary> |
| | 89 | | /// <param name="mask">Subnet mask.</param> |
| | 90 | | /// <returns>Byte CIDR representing the mask.</returns> |
| | 91 | | public static byte MaskToCidr(IPAddress mask) |
| | 92 | | { |
| 0 | 93 | | ArgumentNullException.ThrowIfNull(mask); |
| | 94 | |
|
| 0 | 95 | | byte cidrnet = 0; |
| 0 | 96 | | if (mask.Equals(IPAddress.Any)) |
| | 97 | | { |
| 0 | 98 | | return cidrnet; |
| | 99 | | } |
| | 100 | |
|
| | 101 | | // GetAddressBytes |
| 0 | 102 | | Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? NetworkConstants.IPv4MaskB |
| 0 | 103 | | if (!mask.TryWriteBytes(bytes, out var bytesWritten)) |
| | 104 | | { |
| 0 | 105 | | Console.WriteLine("Unable to write address bytes, only ${bytesWritten} bytes written."); |
| | 106 | | } |
| | 107 | |
|
| 0 | 108 | | var zeroed = false; |
| 0 | 109 | | for (var i = 0; i < bytes.Length; i++) |
| | 110 | | { |
| 0 | 111 | | for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1) |
| | 112 | | { |
| 0 | 113 | | if (zeroed) |
| | 114 | | { |
| | 115 | | // Invalid netmask. |
| 0 | 116 | | return (byte)~cidrnet; |
| | 117 | | } |
| | 118 | |
|
| 0 | 119 | | if ((v & 0x80) == 0) |
| | 120 | | { |
| 0 | 121 | | zeroed = true; |
| | 122 | | } |
| | 123 | | else |
| | 124 | | { |
| 0 | 125 | | cidrnet++; |
| | 126 | | } |
| | 127 | | } |
| | 128 | | } |
| | 129 | |
|
| 0 | 130 | | return cidrnet; |
| | 131 | | } |
| | 132 | |
|
| | 133 | | /// <summary> |
| | 134 | | /// Converts an IPAddress into a string. |
| | 135 | | /// IPv6 addresses are returned in [ ], with their scope removed. |
| | 136 | | /// </summary> |
| | 137 | | /// <param name="address">Address to convert.</param> |
| | 138 | | /// <returns>URI safe conversion of the address.</returns> |
| | 139 | | public static string FormatIPString(IPAddress? address) |
| | 140 | | { |
| 17 | 141 | | if (address is null) |
| | 142 | | { |
| 0 | 143 | | return string.Empty; |
| | 144 | | } |
| | 145 | |
|
| 17 | 146 | | var str = address.ToString(); |
| 17 | 147 | | if (address.AddressFamily == AddressFamily.InterNetworkV6) |
| | 148 | | { |
| 0 | 149 | | int i = str.IndexOf('%', StringComparison.Ordinal); |
| 0 | 150 | | if (i != -1) |
| | 151 | | { |
| 0 | 152 | | str = str.Substring(0, i); |
| | 153 | | } |
| | 154 | |
|
| 0 | 155 | | return $"[{str}]"; |
| | 156 | | } |
| | 157 | |
|
| 17 | 158 | | return str; |
| | 159 | | } |
| | 160 | |
|
| | 161 | | /// <summary> |
| | 162 | | /// Try parsing an array of strings into <see cref="IPNetwork"/> objects, respecting exclusions. |
| | 163 | | /// Elements without a subnet mask will be represented as <see cref="IPNetwork"/> with a single IP. |
| | 164 | | /// </summary> |
| | 165 | | /// <param name="values">Input string array to be parsed.</param> |
| | 166 | | /// <param name="result">Collection of <see cref="IPNetwork"/>.</param> |
| | 167 | | /// <param name="negated">Boolean signaling if negated or not negated values should be parsed.</param> |
| | 168 | | /// <returns><c>True</c> if parsing was successful.</returns> |
| | 169 | | public static bool TryParseToSubnets(string[] values, [NotNullWhen(true)] out IReadOnlyList<IPNetwork>? result, bool |
| | 170 | | { |
| 158 | 171 | | if (values is null || values.Length == 0) |
| | 172 | | { |
| 90 | 173 | | result = null; |
| 90 | 174 | | return false; |
| | 175 | | } |
| | 176 | |
|
| 68 | 177 | | var tmpResult = new List<IPNetwork>(); |
| 296 | 178 | | for (int a = 0; a < values.Length; a++) |
| | 179 | | { |
| 80 | 180 | | if (TryParseToSubnet(values[a], out var innerResult, negated)) |
| | 181 | | { |
| 40 | 182 | | tmpResult.Add(innerResult); |
| | 183 | | } |
| | 184 | | } |
| | 185 | |
|
| 68 | 186 | | result = tmpResult; |
| 68 | 187 | | return tmpResult.Count > 0; |
| | 188 | | } |
| | 189 | |
|
| | 190 | | /// <summary> |
| | 191 | | /// Try parsing a string into an <see cref="IPNetwork"/>, respecting exclusions. |
| | 192 | | /// Inputs without a subnet mask will be represented as <see cref="IPNetwork"/> with a single IP. |
| | 193 | | /// </summary> |
| | 194 | | /// <param name="value">Input string to be parsed.</param> |
| | 195 | | /// <param name="result">An <see cref="IPNetwork"/>.</param> |
| | 196 | | /// <param name="negated">Boolean signaling if negated or not negated values should be parsed.</param> |
| | 197 | | /// <returns><c>True</c> if parsing was successful.</returns> |
| | 198 | | public static bool TryParseToSubnet(ReadOnlySpan<char> value, [NotNullWhen(true)] out IPNetwork? result, bool negate |
| | 199 | | { |
| 232 | 200 | | value = value.Trim(); |
| 232 | 201 | | if (value.Contains('/')) |
| | 202 | | { |
| 190 | 203 | | if (negated && value.StartsWith("!") && IPNetwork.TryParse(value[1..], out result)) |
| | 204 | | { |
| 4 | 205 | | return true; |
| | 206 | | } |
| 186 | 207 | | else if (!negated && IPNetwork.TryParse(value, out result)) |
| | 208 | | { |
| 146 | 209 | | return true; |
| | 210 | | } |
| | 211 | | } |
| 42 | 212 | | else if (IPAddress.TryParse(value, out var address)) |
| | 213 | | { |
| 16 | 214 | | if (address.AddressFamily == AddressFamily.InterNetwork) |
| | 215 | | { |
| 10 | 216 | | result = address.Equals(IPAddress.Any) ? NetworkConstants.IPv4Any : new IPNetwork(address, NetworkConsta |
| 10 | 217 | | return true; |
| | 218 | | } |
| 6 | 219 | | else if (address.AddressFamily == AddressFamily.InterNetworkV6) |
| | 220 | | { |
| 6 | 221 | | result = address.Equals(IPAddress.IPv6Any) ? NetworkConstants.IPv6Any : new IPNetwork(address, NetworkCo |
| 6 | 222 | | return true; |
| | 223 | | } |
| | 224 | | } |
| | 225 | |
|
| 66 | 226 | | result = null; |
| 66 | 227 | | return false; |
| | 228 | | } |
| | 229 | |
|
| | 230 | | /// <summary> |
| | 231 | | /// Attempts to parse a host span. |
| | 232 | | /// </summary> |
| | 233 | | /// <param name="host">Host name to parse.</param> |
| | 234 | | /// <param name="addresses">Object representing the span, if it has successfully been parsed.</param> |
| | 235 | | /// <param name="isIPv4Enabled"><c>true</c> if IPv4 is enabled.</param> |
| | 236 | | /// <param name="isIPv6Enabled"><c>true</c> if IPv6 is enabled.</param> |
| | 237 | | /// <returns><c>true</c> if the parsing is successful, <c>false</c> if not.</returns> |
| | 238 | | public static bool TryParseHost(ReadOnlySpan<char> host, [NotNullWhen(true)] out IPAddress[]? addresses, bool isIPv4 |
| | 239 | | { |
| 261 | 240 | | host = host.Trim(); |
| 261 | 241 | | if (host.IsEmpty) |
| | 242 | | { |
| 5 | 243 | | addresses = null; |
| 5 | 244 | | return false; |
| | 245 | | } |
| | 246 | |
|
| | 247 | | // See if it's an IPv6 with port address e.g. [::1] or [::1]:120. |
| 256 | 248 | | if (host[0] == '[') |
| | 249 | | { |
| 4 | 250 | | int i = host.IndexOf(']'); |
| 4 | 251 | | if (i != -1) |
| | 252 | | { |
| 4 | 253 | | return TryParseHost(host[1..(i - 1)], out addresses); |
| | 254 | | } |
| | 255 | |
|
| 0 | 256 | | addresses = Array.Empty<IPAddress>(); |
| 0 | 257 | | return false; |
| | 258 | | } |
| | 259 | |
|
| 252 | 260 | | var hosts = new List<string>(); |
| 2528 | 261 | | foreach (var splitSpan in host.Split(':')) |
| | 262 | | { |
| 1012 | 263 | | hosts.Add(splitSpan.ToString()); |
| | 264 | | } |
| | 265 | |
|
| 252 | 266 | | if (hosts.Count <= 2) |
| | 267 | | { |
| 143 | 268 | | var firstPart = hosts[0]; |
| | 269 | |
|
| | 270 | | // Is hostname or hostname:port |
| 143 | 271 | | if (FqdnGeneratedRegex().IsMatch(firstPart)) |
| | 272 | | { |
| | 273 | | try |
| | 274 | | { |
| | 275 | | // .NET automatically filters only supported returned addresses based on OS support. |
| 15 | 276 | | addresses = Dns.GetHostAddresses(firstPart); |
| 12 | 277 | | return true; |
| | 278 | | } |
| 3 | 279 | | catch (SocketException) |
| | 280 | | { |
| | 281 | | // Ignore socket errors, as the result value will just be an empty array. |
| 3 | 282 | | } |
| | 283 | | } |
| | 284 | |
|
| | 285 | | // Is an IPv4 or IPv4:port |
| 131 | 286 | | if (IPAddress.TryParse(firstPart.AsSpan().LeftPart('/'), out var address)) |
| | 287 | | { |
| 123 | 288 | | if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIPv4Enabled && isIPv6Enabled)) |
| 123 | 289 | | || ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIPv4Enabled && !isIPv6Enabled))) |
| | 290 | | { |
| 0 | 291 | | addresses = Array.Empty<IPAddress>(); |
| 0 | 292 | | return false; |
| | 293 | | } |
| | 294 | |
|
| 123 | 295 | | addresses = new[] { address }; |
| | 296 | |
|
| | 297 | | // Host name is an IPv4 address, so fake resolve. |
| 123 | 298 | | return true; |
| | 299 | | } |
| | 300 | | } |
| 109 | 301 | | else if (hosts.Count > 0 && hosts.Count <= 9) // 8 octets + port |
| | 302 | | { |
| 109 | 303 | | if (IPAddress.TryParse(host.LeftPart('/'), out var address)) |
| | 304 | | { |
| 107 | 305 | | addresses = new[] { address }; |
| 107 | 306 | | return true; |
| | 307 | | } |
| | 308 | | } |
| | 309 | |
|
| 10 | 310 | | addresses = Array.Empty<IPAddress>(); |
| 10 | 311 | | return false; |
| 12 | 312 | | } |
| | 313 | |
|
| | 314 | | /// <summary> |
| | 315 | | /// Gets the broadcast address for a <see cref="IPNetwork"/>. |
| | 316 | | /// </summary> |
| | 317 | | /// <param name="network">The <see cref="IPNetwork"/>.</param> |
| | 318 | | /// <returns>The broadcast address.</returns> |
| | 319 | | public static IPAddress GetBroadcastAddress(IPNetwork network) |
| | 320 | | { |
| 0 | 321 | | var addressBytes = network.Prefix.GetAddressBytes(); |
| 0 | 322 | | uint ipAddress = BitConverter.ToUInt32(addressBytes, 0); |
| 0 | 323 | | uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressByt |
| 0 | 324 | | uint broadCastIPAddress = ipAddress | ~ipMaskV4; |
| | 325 | |
|
| 0 | 326 | | return new IPAddress(BitConverter.GetBytes(broadCastIPAddress)); |
| | 327 | | } |
| | 328 | | } |