repo creation with initial code after cloning public repo

This commit is contained in:
2026-02-19 07:36:25 -05:00
commit 460884fea3
2860 changed files with 650825 additions and 0 deletions
+133
View File
@@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.NetworkInformation;
using MediaBrowser.Model.Net;
using Microsoft.AspNetCore.Http;
namespace MediaBrowser.Common.Net
{
/// <summary>
/// Interface for the NetworkManager class.
/// </summary>
public interface INetworkManager
{
/// <summary>
/// Event triggered on network changes.
/// </summary>
event EventHandler NetworkChanged;
/// <summary>
/// Gets a value indicating whether IPv4 is enabled.
/// </summary>
bool IsIPv4Enabled { get; }
/// <summary>
/// Gets a value indicating whether IPv6 is enabled.
/// </summary>
bool IsIPv6Enabled { get; }
/// <summary>
/// Calculates the list of interfaces to use for Kestrel.
/// </summary>
/// <returns>A IReadOnlyList{IPData} object containing all the interfaces to bind.
/// If all the interfaces are specified, and none are excluded, it returns zero items
/// to represent any address.</returns>
/// <param name="individualInterfaces">When false, return <see cref="IPAddress.Any"/> or <see cref="IPAddress.IPv6Any"/> for all interfaces.</param>
IReadOnlyList<IPData> GetAllBindInterfaces(bool individualInterfaces = false);
/// <summary>
/// Returns a list containing the loopback interfaces.
/// </summary>
/// <returns>IReadOnlyList{IPData}.</returns>
IReadOnlyList<IPData> GetLoopbacks();
/// <summary>
/// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo)
/// If no bind addresses are specified, an internal interface address is selected.
/// The priority of selection is as follows:-
///
/// The value contained in the startup parameter --published-server-url.
///
/// If the user specified custom subnet overrides, the correct subnet for the source address.
///
/// If the user specified bind interfaces to use:-
/// The bind interface that contains the source subnet.
/// The first bind interface specified that suits best first the source's endpoint. eg. external or internal.
///
/// If the source is from a public subnet address range and the user hasn't specified any bind addresses:-
/// The first public interface that isn't a loopback and contains the source subnet.
/// The first public interface that isn't a loopback.
/// The first internal interface that isn't a loopback.
///
/// If the source is from a private subnet address range and the user hasn't specified any bind addresses:-
/// The first private interface that contains the source subnet.
/// The first private interface that isn't a loopback.
///
/// If no interfaces meet any of these criteria, then a loopback address is returned.
///
/// Interfaces that have been specifically excluded from binding are not used in any of the calculations.
/// </summary>
/// <param name="source">Source of the request.</param>
/// <param name="port">Optional port returned, if it's part of an override.</param>
/// <returns>IP address to use, or loopback address if all else fails.</returns>
string GetBindAddress(HttpRequest source, out int? port);
/// <summary>
/// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo)
/// If no bind addresses are specified, an internal interface address is selected.
/// </summary>
/// <param name="source">IP address of the request.</param>
/// <param name="port">Optional port returned, if it's part of an override.</param>
/// <param name="skipOverrides">Optional boolean denoting if published server overrides should be ignored. Defaults to false.</param>
/// <returns>IP address to use, or loopback address if all else fails.</returns>
string GetBindAddress(IPAddress? source, out int? port, bool skipOverrides = false);
/// <summary>
/// Retrieves the bind address to use in system URLs. (Server Discovery, PlayTo, LiveTV, SystemInfo)
/// If no bind addresses are specified, an internal interface address is selected.
/// (See <see cref="GetBindAddress(IPAddress, out int?, bool)"/>.
/// </summary>
/// <param name="source">Source of the request.</param>
/// <param name="port">Optional port returned, if it's part of an override.</param>
/// <returns>IP address to use, or loopback address if all else fails.</returns>
string GetBindAddress(string source, out int? port);
/// <summary>
/// Returns true if the address is part of the user defined LAN.
/// </summary>
/// <param name="address">IP to check.</param>
/// <returns>True if endpoint is within the LAN range.</returns>
bool IsInLocalNetwork(string address);
/// <summary>
/// Returns true if the address is part of the user defined LAN.
/// </summary>
/// <param name="address">IP to check.</param>
/// <returns>True if endpoint is within the LAN range.</returns>
bool IsInLocalNetwork(IPAddress address);
/// <summary>
/// Attempts to convert the interface name to an IP address.
/// eg. "eth1", or "enp3s5".
/// </summary>
/// <param name="intf">Interface name.</param>
/// <param name="result">Resulting object's IP addresses, if successful.</param>
/// <returns>Success of the operation.</returns>
bool TryParseInterface(string intf, [NotNullWhen(true)] out IReadOnlyList<IPData>? result);
/// <summary>
/// Returns all internal (LAN) bind interface addresses.
/// </summary>
/// <returns>An list of internal (LAN) interfaces addresses.</returns>
IReadOnlyList<IPData> GetInternalBindAddresses();
/// <summary>
/// Checks if <paramref name="remoteIP"/> has access to the server.
/// </summary>
/// <param name="remoteIP">IP address of the client.</param>
/// <returns>The result of evaluating the access policy, <c>Allow</c> if it should be allowed.</returns>
RemoteAccessPolicyResult ShouldAllowServerAccess(IPAddress remoteIP);
}
}
+28
View File
@@ -0,0 +1,28 @@
namespace MediaBrowser.Common.Net
{
/// <summary>
/// Registered http client names.
/// </summary>
public static class NamedClient
{
/// <summary>
/// Gets the value for the default named http client which implements happy eyeballs.
/// </summary>
public const string Default = nameof(Default);
/// <summary>
/// Gets the value for the MusicBrainz named http client.
/// </summary>
public const string MusicBrainz = nameof(MusicBrainz);
/// <summary>
/// Gets the value for the DLNA named http client.
/// </summary>
public const string Dlna = nameof(Dlna);
/// <summary>
/// Non happy eyeballs implementation.
/// </summary>
public const string DirectIp = nameof(DirectIp);
}
}
@@ -0,0 +1,176 @@
#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>
[Obsolete("No longer supported")]
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; }
}
@@ -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);
}
}
@@ -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()
};
}
}
@@ -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;
}
}
@@ -0,0 +1,79 @@
using System.Net;
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>
/// IPv4 Link-Local as defined in RFC 3927.
/// </summary>
public static readonly IPNetwork IPv4RFC3927LinkLocal = new IPNetwork(IPAddress.Parse("169.254.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);
}
+360
View File
@@ -0,0 +1,360 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using Jellyfin.Extensions;
using MediaBrowser.Model.Net;
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 {0} bytes written.", bytesWritten.ToString(CultureInfo.InvariantCulture));
}
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<IPData>? result, bool negated = false)
{
if (values is null || values.Length == 0)
{
result = null;
return false;
}
List<IPData>? tmpResult = null;
for (int a = 0; a < values.Length; a++)
{
if (TryParseToSubnet(values[a], out var innerResult, negated))
{
(tmpResult ??= new()).Add(innerResult);
}
}
result = tmpResult;
return result is not null;
}
/// <summary>
/// Try parsing a string into an <see cref="IPData"/>, respecting exclusions.
/// Inputs without a subnet mask will be represented as <see cref="IPData"/> with a single IP.
/// </summary>
/// <param name="value">Input string to be parsed.</param>
/// <param name="result">An <see cref="IPData"/>.</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 IPData? result, bool negated = false)
{
// If multiple IP addresses are in a comma-separated string, the individual addresses may contain leading and/or trailing whitespace
value = value.Trim();
bool isAddressNegated = false;
if (value.StartsWith('!'))
{
isAddressNegated = true;
value = value[1..]; // Remove leading '!' character
}
if (isAddressNegated != negated)
{
result = default;
return false;
}
var index = value.IndexOf('/');
if (index != -1)
{
if (IPAddress.TryParse(value[..index], out var address) && IPNetwork.TryParse(value, out var subnet))
{
result = new IPData(address, subnet);
return true;
}
}
else if (IPAddress.TryParse(value, out var address))
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
result = address.Equals(IPAddress.Any) ? new IPData(IPAddress.Any, NetworkConstants.IPv4Any) : new IPData(address, new IPNetwork(address, NetworkConstants.MinimumIPv4PrefixSize));
return true;
}
else if (address.AddressFamily == AddressFamily.InterNetworkV6)
{
result = address.Equals(IPAddress.IPv6Any) ? new IPData(IPAddress.IPv6Any, NetworkConstants.IPv6Any) : new IPData(address, new IPNetwork(address, NetworkConstants.MinimumIPv6PrefixSize));
return true;
}
}
result = default;
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.BaseAddress.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));
}
/// <summary>
/// Check if a subnet contains an address. This method also handles IPv4 mapped to IPv6 addresses.
/// </summary>
/// <param name="network">The <see cref="IPNetwork"/>.</param>
/// <param name="address">The <see cref="IPAddress"/>.</param>
/// <returns>Whether the supplied IP is in the supplied network.</returns>
public static bool SubnetContainsAddress(IPNetwork network, IPAddress address)
{
ArgumentNullException.ThrowIfNull(address);
if (address.IsIPv4MappedToIPv6)
{
address = address.MapToIPv4();
}
return network.Contains(address);
}
}
@@ -0,0 +1,29 @@
using System;
namespace MediaBrowser.Common.Net;
/// <summary>
/// Result of <see cref="INetworkManager.ShouldAllowServerAccess" />.
/// </summary>
public enum RemoteAccessPolicyResult
{
/// <summary>
/// The connection should be allowed.
/// </summary>
Allow,
/// <summary>
/// The connection should be rejected since it is not from a local IP and remote access is disabled.
/// </summary>
RejectDueToRemoteAccessDisabled,
/// <summary>
/// The connection should be rejected since it is from a blocklisted IP.
/// </summary>
RejectDueToIPBlocklist,
/// <summary>
/// The connection should be rejected since it is from a remote IP that is not in the allowlist.
/// </summary>
RejectDueToNotAllowlistedRemoteIP,
}