Skip to content

The Free Software Media System - Server Backend & API

Merge branch 'master' into network-rewrite

Shadowghost7b90fcd0531e
diff --cc Emby.Server.Implementations/Net/SocketFactory.cs
index a1baf30064,303875df55..02e45e6899
--- a/Emby.Server.Implementations/Net/SocketFactory.cs
+++ b/Emby.Server.Implementations/Net/SocketFactory.cs
@@@ -61,18 -61,10 +61,15 @@@ namespace Emby.Server.Implementations.N
}
/// <inheritdoc />
- public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, int multicastTimeToLive, int localPort)
+ public ISocket CreateUdpMulticastSocket(IPAddress ipAddress, IPAddress bindIpAddress, int multicastTimeToLive, int localPort)
{
- if (ipAddress == null)
- {
- throw new ArgumentNullException(nameof(ipAddress));
- }
+ ArgumentNullException.ThrowIfNull(ipAddress);
+ if (bindIpAddress == null)
+ {
+ bindIpAddress = IPAddress.Any;
+ }
+
if (multicastTimeToLive <= 0)
{
throw new ArgumentException("multicastTimeToLive cannot be zero or less.", nameof(multicastTimeToLive));
diff --cc Jellyfin.Networking/Manager/NetworkManager.cs
index 146340989b,9e06cdfe71..333afd7484
--- a/Jellyfin.Networking/Manager/NetworkManager.cs
+++ b/Jellyfin.Networking/Manager/NetworkManager.cs
@@@ -77,14 -102,14 +77,17 @@@ namespace Jellyfin.Networking.Manage
#pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in UpdateSettings function. Compiler doesn't yet recognise this.
public NetworkManager(IConfigurationManager configurationManager, ILogger<NetworkManager> logger)
{
-- _logger = logger ?? throw new ArgumentNullException(nameof(logger));
-- _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager));
++ ArgumentNullException.ThrowIfNull(logger);
++ ArgumentNullException.ThrowIfNull(configurationManager);
+
- _interfaceAddresses = new Collection<IPObject>();
++ _logger = logger;
++ _configurationManager = configurationManager;
+ _initLock = new();
+ _interfaces = new List<IPData>();
_macAddresses = new List<PhysicalAddress>();
- _interfaceNames = new Dictionary<string, int>();
- _publishedServerUrls = new Dictionary<IPNetAddress, string>();
+ _publishedServerUrls = new Dictionary<IPData, string>();
_eventFireLock = new object();
+ _remoteAddressFilter = new List<IPNetwork>();
UpdateSettings(_configurationManager.GetNetworkConfiguration());
@@@ -497,10 -590,18 +500,12 @@@
/// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param>
public void UpdateSettings(object configuration)
{
-- NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration));
-
- IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4;
- IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6;
++ ArgumentNullException.ThrowIfNull(configuration);
+
- if (!IsIP6Enabled && !IsIP4Enabled)
- {
- _logger.LogError("IPv4 and IPv6 cannot both be disabled.");
- IsIP4Enabled = true;
- }
++ var config = (NetworkConfiguration)configuration;
- TrustAllIP6Interfaces = config.TrustAllIP6Interfaces;
+ InitialiseLan(config);
+ InitialiseRemote(config);
if (string.IsNullOrEmpty(MockNetworkSettings))
{
@@@ -731,133 -894,259 +736,130 @@@
}
else
{
- var replacement = parts[1].Trim();
- if (string.Equals(parts[0], "all", StringComparison.OrdinalIgnoreCase))
- {
- _publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement;
- }
- else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase))
- {
- _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement;
- }
- else if (TryParseInterface(parts[0], out Collection<IPObject>? addresses) && addresses != null)
- {
- foreach (IPNetAddress na in addresses)
- {
- _publishedServerUrls[na] = replacement;
- }
- }
- else if (IPNetAddress.TryParse(parts[0], out IPNetAddress result))
- {
- _publishedServerUrls[result] = replacement;
- }
- else
- {
- _logger.LogError("Unable to parse bind ip address. {Parts}", parts[1]);
- }
+ _logger.LogInformation("{Source}: Using BindAddress {Address}", source, res);
}
- }
- }
- }
- /// <summary>
- /// Initialises the network bind addresses.
- /// </summary>
- private void InitialiseBind(NetworkConfiguration config)
- {
- lock (_intLock)
- {
- string[] lanAddresses = config.LocalNetworkAddresses;
+ return res;
+ }
- // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded.
- if (config.IgnoreVirtualInterfaces)
+ // No preference given, so move on to bind addresses.
+ if (MatchesBindInterface(source, isExternal, out result))
{
- // each virtual interface name must be prepended with the exclusion symbol !
- var virtualInterfaceNames = config.VirtualInterfaceNames.Split(',').Select(p => "!" + p).ToArray();
- if (lanAddresses.Length > 0)
- {
- var newList = new string[lanAddresses.Length + virtualInterfaceNames.Length];
- Array.Copy(lanAddresses, newList, lanAddresses.Length);
- Array.Copy(virtualInterfaceNames, 0, newList, lanAddresses.Length, virtualInterfaceNames.Length);
- lanAddresses = newList;
- }
- else
- {
- lanAddresses = virtualInterfaceNames;
- }
+ return result;
}
- // Read and parse bind addresses and exclusions, removing ones that don't exist.
- _bindAddresses = CreateIPCollection(lanAddresses).ThatAreContainedInNetworks(_interfaceAddresses);
- _bindExclusions = CreateIPCollection(lanAddresses, true).ThatAreContainedInNetworks(_interfaceAddresses);
- _logger.LogInformation("Using bind addresses: {0}", _bindAddresses.AsString());
- _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions.AsString());
+ if (isExternal && MatchesExternalInterface(source, out result))
+ {
+ return result;
+ }
}
- }
- /// <summary>
- /// Initialises the remote address values.
- /// </summary>
- private void InitialiseRemote(NetworkConfiguration config)
- {
- lock (_intLock)
- {
- RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter);
- }
- }
+ // Get the first LAN interface address that's not excluded and not a loopback address.
+ var availableInterfaces = _interfaces.Where(x => !IPAddress.IsLoopback(x.Address))
+ .OrderByDescending(x => IsInLocalNetwork(x.Address))
+ .ThenBy(x => x.Index);
- /// <summary>
- /// Initialises internal LAN cache settings.
- /// </summary>
- private void InitialiseLAN(NetworkConfiguration config)
- {
- lock (_intLock)
+ if (availableInterfaces.Any())
{
- _logger.LogDebug("Refreshing LAN information.");
-
- // Get configuration options.
- string[] subnets = config.LocalNetworkSubnets;
-
- // Create lists from user settings.
-
- _lanSubnets = CreateIPCollection(subnets);
- _excludedSubnets = CreateIPCollection(subnets, true).AsNetworks();
-
- // If no LAN addresses are specified - all private subnets are deemed to be the LAN
- _usingPrivateAddresses = _lanSubnets.Count == 0;
-
- // NOTE: The order of the commands generating the collection in this statement matters.
- // Altering the order will cause the collections to be created incorrectly.
- if (_usingPrivateAddresses)
+ if (source != null)
{
- _logger.LogDebug("Using LAN interface addresses as user provided no LAN details.");
- // Internal interfaces must be private and not excluded.
- _internalInterfaces = CreateCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.ContainsAddress(i)));
-
- // Subnets are the same as the calculated internal interface.
- _lanSubnets = new Collection<IPObject>();
-
- if (IsIP6Enabled)
+ foreach (var intf in availableInterfaces)
{
- _lanSubnets.AddItem(IPNetAddress.Parse("fc00::/7")); // ULA
- _lanSubnets.AddItem(IPNetAddress.Parse("fe80::/10")); // Site local
+ if (intf.Address.Equals(source))
+ {
+ result = NetworkExtensions.FormatIpString(intf.Address);
+ _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface: {Result}", source, result);
+ return result;
+ }
}
- if (IsIP4Enabled)
+ // Does the request originate in one of the interface subnets?
+ // (For systems with multiple internal network cards, and multiple subnets)
+ foreach (var intf in availableInterfaces)
{
- _lanSubnets.AddItem(IPNetAddress.Parse("10.0.0.0/8"));
- _lanSubnets.AddItem(IPNetAddress.Parse("172.16.0.0/12"));
- _lanSubnets.AddItem(IPNetAddress.Parse("192.168.0.0/16"));
+ if (intf.Subnet.Contains(source))
+ {
+ result = NetworkExtensions.FormatIpString(intf.Address);
+ _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range: {Result}", source, result);
+ return result;
+ }
}
}
- else
- {
- // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet.
- _internalInterfaces = CreateCollection(_interfaceAddresses.Where(IsInLocalNetwork));
- }
- _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets.AsString());
- _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets.AsString());
- _logger.LogInformation("Using LAN addresses: {0}", _lanSubnets.Exclude(_excludedSubnets, true).AsNetworks().AsString());
+ result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address);
+ _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface: {Result}", source, result);
+ return result;
}
+
+ // There isn't any others, so we'll use the loopback.
+ result = IsIpv4Enabled && !IsIpv6Enabled ? "127.0.0.1" : "::1";
+ _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result);
+ return result;
}
- /// <summary>
- /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state.
- /// Generate a list of all active mac addresses that aren't loopback addresses.
- /// </summary>
- private void InitialiseInterfaces()
+ /// <inheritdoc/>
+ public IReadOnlyList<IPData> GetInternalBindAddresses()
{
- lock (_intLock)
- {
- _logger.LogDebug("Refreshing interfaces.");
+ // Select all local bind addresses
+ return _interfaces.Where(x => IsInLocalNetwork(x.Address))
+ .OrderBy(x => x.Index)
+ .ToList();
+ }
- _interfaceNames.Clear();
- _interfaceAddresses.Clear();
- _macAddresses.Clear();
+ /// <inheritdoc/>
+ public bool IsInLocalNetwork(string address)
+ {
+ if (IPAddress.TryParse(address, out var ep))
+ {
+ return IPAddress.IsLoopback(ep) || (_lanSubnets.Any(x => x.Contains(ep)) && !_excludedSubnets.Any(x => x.Contains(ep)));
+ }
- try
+ if (NetworkExtensions.TryParseHost(address, out var addresses, IsIpv4Enabled, IsIpv6Enabled))
+ {
+ bool match = false;
+ foreach (var ept in addresses)
{
- IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces()
- .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up);
+ match |= IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept)));
+ }
- foreach (NetworkInterface adapter in nics)
- {
- try
- {
- IPInterfaceProperties ipProperties = adapter.GetIPProperties();
- PhysicalAddress mac = adapter.GetPhysicalAddress();
+ return match;
+ }
- // populate mac list
- if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac != null && mac != PhysicalAddress.None)
- {
- _macAddresses.Add(mac);
- }
+ return false;
+ }
- // populate interface address list
- foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses)
- {
- if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork)
- {
- IPNetAddress nw = new IPNetAddress(info.Address, IPObject.MaskToCidr(info.IPv4Mask))
- {
- // Keep the number of gateways on this interface, along with its index.
- Tag = ipProperties.GetIPv4Properties().Index
- };
-
- int tag = nw.Tag;
- if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback())
- {
- // -ve Tags signify the interface has a gateway.
- nw.Tag *= -1;
- }
-
- _interfaceAddresses.AddItem(nw, false);
-
- // Store interface name so we can use the name in Collections.
- _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
- _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
- }
- else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6)
- {
- IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength)
- {
- // Keep the number of gateways on this interface, along with its index.
- Tag = ipProperties.GetIPv6Properties().Index
- };
-
- int tag = nw.Tag;
- if (ipProperties.GatewayAddresses.Count > 0 && !nw.IsLoopback())
- {
- // -ve Tags signify the interface has a gateway.
- nw.Tag *= -1;
- }
-
- _interfaceAddresses.AddItem(nw, false);
-
- // Store interface name so we can use the name in Collections.
- _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
- _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
- }
- }
- }
-#pragma warning disable CA1031 // Do not catch general exception types
- catch (Exception ex)
- {
- // Ignore error, and attempt to continue.
- _logger.LogError(ex, "Error encountered parsing interfaces.");
- }
-#pragma warning restore CA1031 // Do not catch general exception types
- }
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "Error in InitialiseInterfaces.");
- }
+ /// <inheritdoc/>
+ public bool IsInLocalNetwork(IPAddress address)
+ {
- if (address == null)
- {
- throw new ArgumentNullException(nameof(address));
- }
++ ArgumentNullException.ThrowIfNull(address);
- // If for some reason we don't have an interface info, resolve our DNS name.
- if (_interfaceAddresses.Count == 0)
- {
- _logger.LogError("No interfaces information available. Resolving DNS name.");
- IPHost host = new IPHost(Dns.GetHostName());
- foreach (var a in host.GetAddresses())
- {
- _interfaceAddresses.AddItem(a);
- }
+ // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
+ if (TrustAllIpv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
+ {
+ return true;
+ }
- if (_interfaceAddresses.Count == 0)
- {
- _logger.LogWarning("No interfaces information available. Using loopback.");
- }
- }
+ // As private addresses can be redefined by Configuration.LocalNetworkAddresses
+ var match = CheckIfLanAndNotExcluded(address);
- if (IsIP4Enabled)
- {
- _interfaceAddresses.AddItem(IPNetAddress.IP4Loopback);
- }
+ return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback) || match;
+ }
- if (IsIP6Enabled)
- {
- _interfaceAddresses.AddItem(IPNetAddress.IP6Loopback);
- }
+ private bool CheckIfLanAndNotExcluded(IPAddress address)
+ {
+ bool match = false;
+ foreach (var lanSubnet in _lanSubnets)
+ {
+ match |= lanSubnet.Contains(address);
+ }
- _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count);
- _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses.AsString());
+ foreach (var excludedSubnet in _excludedSubnets)
+ {
+ match &= !excludedSubnet.Contains(address);
}
+
+ NetworkExtensions.IsIPv6LinkLocal(address);
+ return match;
}
/// <summary>
diff --cc MediaBrowser.Common/Net/NetworkExtensions.cs
index 316c2ebcd1,7ad0058540..3d7d58b273
--- a/MediaBrowser.Common/Net/NetworkExtensions.cs
+++ b/MediaBrowser.Common/Net/NetworkExtensions.cs
@@@ -13,42 -9,32 +13,39 @@@ namespace MediaBrowser.Common.Ne
/// </summary>
public static class NetworkExtensions
{
+ // 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
+ private static readonly Regex _fqdnRegex = new Regex(@"(?im)^(?!:\/\/)(?=.{1,255}$)((.{1,63}\.){0,127}(?![0-9]*$)[a-z0-9-]+\.?)(:(\d){1,5}){0,1}$");
+
/// <summary>
- /// Add an address to the collection.
+ /// Returns true if the IPAddress contains an IP6 Local link address.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="ip">Item to add.</param>
- public static void AddItem(this Collection<IPObject> source, IPAddress ip)
+ /// <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)
{
- if (address == null)
- {
- throw new ArgumentNullException(nameof(address));
- }
- if (!source.ContainsAddress(ip))
++ ArgumentNullException.ThrowIfNull(address);
+
+ if (address.IsIPv4MappedToIPv6)
{
- source.Add(new IPNetAddress(ip, 32));
+ address = address.MapToIPv4();
}
- }
- /// <summary>
- /// Adds a network to the collection.
- /// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="item">Item to add.</param>
- /// <param name="itemsAreNetworks">If <c>true</c> the values are treated as subnets.
- /// If <b>false</b> items are addresses.</param>
- public static void AddItem(this Collection<IPObject> source, IPObject item, bool itemsAreNetworks = true)
- {
- if (!source.ContainsAddress(item) || !itemsAreNetworks)
+ if (address.AddressFamily != AddressFamily.InterNetworkV6)
{
- source.Add(item);
+ 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>
@@@ -68,45 -48,31 +65,42 @@@
}
/// <summary>
- /// Returns true if the collection contains an item with the ip address,
- /// or the ip address falls within any of the collection's network ranges.
+ /// Convert a subnet mask to a CIDR. IPv4 only.
+ /// https://stackoverflow.com/questions/36954345/get-cidr-from-netmask.
/// </summary>
- /// <param name="source">The <see cref="Collection{IPObject}"/>.</param>
- /// <param name="item">The item to look for.</param>
- /// <returns>True if the collection contains the item.</returns>
- public static bool ContainsAddress(this Collection<IPObject> source, IPAddress item)
+ /// <param name="mask">Subnet mask.</param>
+ /// <returns>Byte CIDR representing the mask.</returns>
+ public static byte MaskToCidr(IPAddress mask)
{
- if (mask == null)
- if (source.Count == 0)
-- {
- throw new ArgumentNullException(nameof(mask));
- return false;
-- }
-
- ArgumentNullException.ThrowIfNull(item);
++ ArgumentNullException.ThrowIfNull(mask);
- if (item.IsIPv4MappedToIPv6)
+ byte cidrnet = 0;
+ if (!mask.Equals(IPAddress.Any))
{
- item = item.MapToIPv4();
- }
+ // GetAddressBytes
+ Span<byte> bytes = stackalloc byte[mask.AddressFamily == AddressFamily.InterNetwork ? 4 : 16];
+ mask.TryWriteBytes(bytes, out _);
- foreach (var i in source)
- {
- if (i.Contains(item))
+ var zeroed = false;
+ for (var i = 0; i < bytes.Length; i++)
{
- return true;
+ 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++;
+ }
+ }
}
}