< Summary - Jellyfin

Information
Class: MediaBrowser.Common.Net.NetworkUtils
Assembly: MediaBrowser.Common
File(s): /srv/git/jellyfin/MediaBrowser.Common/Net/NetworkUtils.cs
Line coverage
53%
Covered lines: 58
Uncovered lines: 51
Coverable lines: 109
Total lines: 328
Line coverage: 53.2%
Branch coverage
61%
Covered branches: 55
Total branches: 90
Branch coverage: 61.1%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
IsIPv6LinkLocal(...)0%4260%
CidrToMask(...)0%620%
CidrToMask(...)0%620%
MaskToCidr(...)0%210140%
FormatIPString(...)33.33%12.17644.44%
TryParseToSubnets(...)100%88100%
TryParseToSubnet(...)90.9%2222100%
TryParseHost(...)83.33%31.473088.23%
GetBroadcastAddress(...)100%210%

File(s)

/srv/git/jellyfin/MediaBrowser.Common/Net/NetworkUtils.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Diagnostics.CodeAnalysis;
 4using System.Net;
 5using System.Net.Sockets;
 6using System.Text.RegularExpressions;
 7using Jellyfin.Extensions;
 8using IPNetwork = Microsoft.AspNetCore.HttpOverrides.IPNetwork;
 9
 10namespace MediaBrowser.Common.Net;
 11
 12/// <summary>
 13/// Defines the <see cref="NetworkUtils" />.
 14/// </summary>
 15public 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    {
 033        ArgumentNullException.ThrowIfNull(address);
 34
 035        if (address.IsIPv4MappedToIPv6)
 36        {
 037            address = address.MapToIPv4();
 38        }
 39
 040        if (address.AddressFamily != AddressFamily.InterNetworkV6)
 41        {
 042            return false;
 43        }
 44
 45        // GetAddressBytes
 046        Span<byte> octet = stackalloc byte[16];
 047        address.TryWriteBytes(octet, out _);
 048        uint word = (uint)(octet[0] << 8) + octet[1];
 49
 050        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    {
 061        uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? NetworkConstants.MinimumIPv4PrefixSize : Netw
 062        addr = ((addr & 0xff000000) >> 24)
 063                | ((addr & 0x00ff0000) >> 8)
 064                | ((addr & 0x0000ff00) << 8)
 065                | ((addr & 0x000000ff) << 24);
 066        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    {
 077        uint addr = 0xFFFFFFFF << ((family == AddressFamily.InterNetwork ? NetworkConstants.MinimumIPv4PrefixSize : Netw
 078        addr = ((addr & 0xff000000) >> 24)
 079                | ((addr & 0x00ff0000) >> 8)
 080                | ((addr & 0x0000ff00) << 8)
 081                | ((addr & 0x000000ff) << 24);
 082        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    {
 093        ArgumentNullException.ThrowIfNull(mask);
 94
 095        byte cidrnet = 0;
 096        if (mask.Equals(IPAddress.Any))
 97        {
 098            return cidrnet;
 99        }
 100
 101        // GetAddressBytes
 0102        Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? NetworkConstants.IPv4MaskB
 0103        if (!mask.TryWriteBytes(bytes, out var bytesWritten))
 104        {
 0105            Console.WriteLine("Unable to write address bytes, only ${bytesWritten} bytes written.");
 106        }
 107
 0108        var zeroed = false;
 0109        for (var i = 0; i < bytes.Length; i++)
 110        {
 0111            for (int v = bytes[i]; (v & 0xFF) != 0; v <<= 1)
 112            {
 0113                if (zeroed)
 114                {
 115                    // Invalid netmask.
 0116                    return (byte)~cidrnet;
 117                }
 118
 0119                if ((v & 0x80) == 0)
 120                {
 0121                    zeroed = true;
 122                }
 123                else
 124                {
 0125                    cidrnet++;
 126                }
 127            }
 128        }
 129
 0130        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    {
 17141        if (address is null)
 142        {
 0143            return string.Empty;
 144        }
 145
 17146        var str = address.ToString();
 17147        if (address.AddressFamily == AddressFamily.InterNetworkV6)
 148        {
 0149            int i = str.IndexOf('%', StringComparison.Ordinal);
 0150            if (i != -1)
 151            {
 0152                str = str.Substring(0, i);
 153            }
 154
 0155            return $"[{str}]";
 156        }
 157
 17158        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    {
 158171        if (values is null || values.Length == 0)
 172        {
 90173            result = null;
 90174            return false;
 175        }
 176
 68177        var tmpResult = new List<IPNetwork>();
 296178        for (int a = 0; a < values.Length; a++)
 179        {
 80180            if (TryParseToSubnet(values[a], out var innerResult, negated))
 181            {
 40182                tmpResult.Add(innerResult);
 183            }
 184        }
 185
 68186        result = tmpResult;
 68187        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    {
 232200        value = value.Trim();
 232201        if (value.Contains('/'))
 202        {
 190203            if (negated && value.StartsWith("!") && IPNetwork.TryParse(value[1..], out result))
 204            {
 4205                return true;
 206            }
 186207            else if (!negated && IPNetwork.TryParse(value, out result))
 208            {
 146209                return true;
 210            }
 211        }
 42212        else if (IPAddress.TryParse(value, out var address))
 213        {
 16214            if (address.AddressFamily == AddressFamily.InterNetwork)
 215            {
 10216                result = address.Equals(IPAddress.Any) ? NetworkConstants.IPv4Any : new IPNetwork(address, NetworkConsta
 10217                return true;
 218            }
 6219            else if (address.AddressFamily == AddressFamily.InterNetworkV6)
 220            {
 6221                result = address.Equals(IPAddress.IPv6Any) ? NetworkConstants.IPv6Any : new IPNetwork(address, NetworkCo
 6222                return true;
 223            }
 224        }
 225
 66226        result = null;
 66227        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    {
 261240        host = host.Trim();
 261241        if (host.IsEmpty)
 242        {
 5243            addresses = null;
 5244            return false;
 245        }
 246
 247        // See if it's an IPv6 with port address e.g. [::1] or [::1]:120.
 256248        if (host[0] == '[')
 249        {
 4250            int i = host.IndexOf(']');
 4251            if (i != -1)
 252            {
 4253                return TryParseHost(host[1..(i - 1)], out addresses);
 254            }
 255
 0256            addresses = Array.Empty<IPAddress>();
 0257            return false;
 258        }
 259
 252260        var hosts = new List<string>();
 2528261        foreach (var splitSpan in host.Split(':'))
 262        {
 1012263            hosts.Add(splitSpan.ToString());
 264        }
 265
 252266        if (hosts.Count <= 2)
 267        {
 143268            var firstPart = hosts[0];
 269
 270            // Is hostname or hostname:port
 143271            if (FqdnGeneratedRegex().IsMatch(firstPart))
 272            {
 273                try
 274                {
 275                    // .NET automatically filters only supported returned addresses based on OS support.
 15276                    addresses = Dns.GetHostAddresses(firstPart);
 12277                    return true;
 278                }
 3279                catch (SocketException)
 280                {
 281                    // Ignore socket errors, as the result value will just be an empty array.
 3282                }
 283            }
 284
 285            // Is an IPv4 or IPv4:port
 131286            if (IPAddress.TryParse(firstPart.AsSpan().LeftPart('/'), out var address))
 287            {
 123288                if (((address.AddressFamily == AddressFamily.InterNetwork) && (!isIPv4Enabled && isIPv6Enabled))
 123289                    || ((address.AddressFamily == AddressFamily.InterNetworkV6) && (isIPv4Enabled && !isIPv6Enabled)))
 290                {
 0291                    addresses = Array.Empty<IPAddress>();
 0292                    return false;
 293                }
 294
 123295                addresses = new[] { address };
 296
 297                // Host name is an IPv4 address, so fake resolve.
 123298                return true;
 299            }
 300        }
 109301        else if (hosts.Count > 0 && hosts.Count <= 9) // 8 octets + port
 302        {
 109303            if (IPAddress.TryParse(host.LeftPart('/'), out var address))
 304            {
 107305                addresses = new[] { address };
 107306                return true;
 307            }
 308        }
 309
 10310        addresses = Array.Empty<IPAddress>();
 10311        return false;
 12312    }
 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    {
 0321        var addressBytes = network.Prefix.GetAddressBytes();
 0322        uint ipAddress = BitConverter.ToUInt32(addressBytes, 0);
 0323        uint ipMaskV4 = BitConverter.ToUInt32(CidrToMask(network.PrefixLength, AddressFamily.InterNetwork).GetAddressByt
 0324        uint broadCastIPAddress = ipAddress | ~ipMaskV4;
 325
 0326        return new IPAddress(BitConverter.GetBytes(broadCastIPAddress));
 327    }
 328}