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