| | | 1 | | using System; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Diagnostics.CodeAnalysis; |
| | | 4 | | using System.Globalization; |
| | | 5 | | using System.Linq; |
| | | 6 | | using System.Net; |
| | | 7 | | using System.Net.NetworkInformation; |
| | | 8 | | using System.Net.Sockets; |
| | | 9 | | using System.Threading; |
| | | 10 | | using J2N.Collections.Generic.Extensions; |
| | | 11 | | using MediaBrowser.Common.Configuration; |
| | | 12 | | using MediaBrowser.Common.Net; |
| | | 13 | | using MediaBrowser.Model.Net; |
| | | 14 | | using Microsoft.AspNetCore.Http; |
| | | 15 | | using Microsoft.Extensions.Configuration; |
| | | 16 | | using Microsoft.Extensions.Logging; |
| | | 17 | | using static MediaBrowser.Controller.Extensions.ConfigurationExtensions; |
| | | 18 | | using IConfigurationManager = MediaBrowser.Common.Configuration.IConfigurationManager; |
| | | 19 | | using IPNetwork = Microsoft.AspNetCore.HttpOverrides.IPNetwork; |
| | | 20 | | |
| | | 21 | | namespace Jellyfin.Networking.Manager; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Class to take care of network interface management. |
| | | 25 | | /// </summary> |
| | | 26 | | public class NetworkManager : INetworkManager, IDisposable |
| | | 27 | | { |
| | | 28 | | /// <summary> |
| | | 29 | | /// Threading lock for network properties. |
| | | 30 | | /// </summary> |
| | | 31 | | private readonly Lock _initLock; |
| | | 32 | | |
| | | 33 | | private readonly ILogger<NetworkManager> _logger; |
| | | 34 | | |
| | | 35 | | private readonly IConfigurationManager _configurationManager; |
| | | 36 | | |
| | | 37 | | private readonly IConfiguration _startupConfig; |
| | | 38 | | |
| | | 39 | | private readonly Lock _networkEventLock; |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Holds the published server URLs and the IPs to use them on. |
| | | 43 | | /// </summary> |
| | | 44 | | private IReadOnlyList<PublishedServerUriOverride> _publishedServerUrls; |
| | | 45 | | |
| | | 46 | | private IReadOnlyList<IPNetwork> _remoteAddressFilter; |
| | | 47 | | |
| | | 48 | | /// <summary> |
| | | 49 | | /// Used to stop "event-racing conditions". |
| | | 50 | | /// </summary> |
| | | 51 | | private bool _eventfire; |
| | | 52 | | |
| | | 53 | | /// <summary> |
| | | 54 | | /// Dictionary containing interface addresses and their subnets. |
| | | 55 | | /// </summary> |
| | | 56 | | private List<IPData> _interfaces; |
| | | 57 | | |
| | | 58 | | /// <summary> |
| | | 59 | | /// Unfiltered user defined LAN subnets (<see cref="NetworkConfiguration.LocalNetworkSubnets"/>) |
| | | 60 | | /// or internal interface network subnets if undefined by user. |
| | | 61 | | /// </summary> |
| | | 62 | | private IReadOnlyList<IPNetwork> _lanSubnets; |
| | | 63 | | |
| | | 64 | | /// <summary> |
| | | 65 | | /// User defined list of subnets to excluded from the LAN. |
| | | 66 | | /// </summary> |
| | | 67 | | private IReadOnlyList<IPNetwork> _excludedSubnets; |
| | | 68 | | |
| | | 69 | | /// <summary> |
| | | 70 | | /// True if this object is disposed. |
| | | 71 | | /// </summary> |
| | | 72 | | private bool _disposed; |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// Initializes a new instance of the <see cref="NetworkManager"/> class. |
| | | 76 | | /// </summary> |
| | | 77 | | /// <param name="configurationManager">The <see cref="IConfigurationManager"/> instance.</param> |
| | | 78 | | /// <param name="startupConfig">The <see cref="IConfiguration"/> instance holding startup parameters.</param> |
| | | 79 | | /// <param name="logger">Logger to use for messages.</param> |
| | | 80 | | public NetworkManager(IConfigurationManager configurationManager, IConfiguration startupConfig, ILogger<NetworkManag |
| | | 81 | | { |
| | 79 | 82 | | ArgumentNullException.ThrowIfNull(logger); |
| | 79 | 83 | | ArgumentNullException.ThrowIfNull(configurationManager); |
| | | 84 | | |
| | 79 | 85 | | _logger = logger; |
| | 79 | 86 | | _configurationManager = configurationManager; |
| | 79 | 87 | | _startupConfig = startupConfig; |
| | 79 | 88 | | _initLock = new(); |
| | 79 | 89 | | _interfaces = new List<IPData>(); |
| | 79 | 90 | | _publishedServerUrls = new List<PublishedServerUriOverride>(); |
| | 79 | 91 | | _networkEventLock = new(); |
| | 79 | 92 | | _remoteAddressFilter = new List<IPNetwork>(); |
| | | 93 | | |
| | 79 | 94 | | _ = bool.TryParse(startupConfig[DetectNetworkChangeKey], out var detectNetworkChange); |
| | | 95 | | |
| | 79 | 96 | | UpdateSettings(_configurationManager.GetNetworkConfiguration()); |
| | | 97 | | |
| | 79 | 98 | | if (detectNetworkChange) |
| | | 99 | | { |
| | 21 | 100 | | NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged; |
| | 21 | 101 | | NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged; |
| | | 102 | | } |
| | | 103 | | |
| | 79 | 104 | | _configurationManager.NamedConfigurationUpdated += ConfigurationUpdated; |
| | 79 | 105 | | } |
| | | 106 | | |
| | | 107 | | /// <summary> |
| | | 108 | | /// Event triggered on network changes. |
| | | 109 | | /// </summary> |
| | | 110 | | public event EventHandler? NetworkChanged; |
| | | 111 | | |
| | | 112 | | /// <summary> |
| | | 113 | | /// Gets or sets a value indicating whether testing is taking place. |
| | | 114 | | /// </summary> |
| | 3 | 115 | | public static string MockNetworkSettings { get; set; } = string.Empty; |
| | | 116 | | |
| | | 117 | | /// <summary> |
| | | 118 | | /// Gets a value indicating whether IP4 is enabled. |
| | | 119 | | /// </summary> |
| | 249 | 120 | | public bool IsIPv4Enabled => _configurationManager.GetNetworkConfiguration().EnableIPv4; |
| | | 121 | | |
| | | 122 | | /// <summary> |
| | | 123 | | /// Gets a value indicating whether IP6 is enabled. |
| | | 124 | | /// </summary> |
| | 221 | 125 | | public bool IsIPv6Enabled => _configurationManager.GetNetworkConfiguration().EnableIPv6; |
| | | 126 | | |
| | | 127 | | /// <summary> |
| | | 128 | | /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal. |
| | | 129 | | /// </summary> |
| | | 130 | | public bool TrustAllIPv6Interfaces { get; private set; } |
| | | 131 | | |
| | | 132 | | /// <summary> |
| | | 133 | | /// Gets the Published server override list. |
| | | 134 | | /// </summary> |
| | 0 | 135 | | public IReadOnlyList<PublishedServerUriOverride> PublishedServerUrls => _publishedServerUrls; |
| | | 136 | | |
| | | 137 | | /// <inheritdoc/> |
| | | 138 | | public void Dispose() |
| | | 139 | | { |
| | 58 | 140 | | Dispose(true); |
| | 58 | 141 | | GC.SuppressFinalize(this); |
| | 58 | 142 | | } |
| | | 143 | | |
| | | 144 | | /// <summary> |
| | | 145 | | /// Handler for network change events. |
| | | 146 | | /// </summary> |
| | | 147 | | /// <param name="sender">Sender.</param> |
| | | 148 | | /// <param name="e">A <see cref="NetworkAvailabilityEventArgs"/> containing network availability information.</param |
| | | 149 | | private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e) |
| | | 150 | | { |
| | 0 | 151 | | _logger.LogDebug("Network availability changed."); |
| | 0 | 152 | | HandleNetworkChange(); |
| | 0 | 153 | | } |
| | | 154 | | |
| | | 155 | | /// <summary> |
| | | 156 | | /// Handler for network change events. |
| | | 157 | | /// </summary> |
| | | 158 | | /// <param name="sender">Sender.</param> |
| | | 159 | | /// <param name="e">An <see cref="EventArgs"/>.</param> |
| | | 160 | | private void OnNetworkAddressChanged(object? sender, EventArgs e) |
| | | 161 | | { |
| | 0 | 162 | | _logger.LogDebug("Network address change detected."); |
| | 0 | 163 | | HandleNetworkChange(); |
| | 0 | 164 | | } |
| | | 165 | | |
| | | 166 | | /// <summary> |
| | | 167 | | /// Triggers our event, and re-loads interface information. |
| | | 168 | | /// </summary> |
| | | 169 | | private void HandleNetworkChange() |
| | 0 | 170 | | { |
| | | 171 | | lock (_networkEventLock) |
| | | 172 | | { |
| | 0 | 173 | | if (!_eventfire) |
| | | 174 | | { |
| | | 175 | | // As network events tend to fire one after the other only fire once every second. |
| | 0 | 176 | | _eventfire = true; |
| | 0 | 177 | | OnNetworkChange(); |
| | | 178 | | } |
| | 0 | 179 | | } |
| | 0 | 180 | | } |
| | | 181 | | |
| | | 182 | | /// <summary> |
| | | 183 | | /// Waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succes |
| | | 184 | | /// </summary> |
| | | 185 | | private void OnNetworkChange() |
| | | 186 | | { |
| | | 187 | | try |
| | | 188 | | { |
| | 0 | 189 | | Thread.Sleep(2000); |
| | 0 | 190 | | var networkConfig = _configurationManager.GetNetworkConfiguration(); |
| | 0 | 191 | | if (IsIPv6Enabled && !Socket.OSSupportsIPv6) |
| | | 192 | | { |
| | 0 | 193 | | UpdateSettings(networkConfig); |
| | | 194 | | } |
| | | 195 | | else |
| | | 196 | | { |
| | 0 | 197 | | InitializeInterfaces(); |
| | 0 | 198 | | InitializeLan(networkConfig); |
| | 0 | 199 | | EnforceBindSettings(networkConfig); |
| | | 200 | | } |
| | | 201 | | |
| | 0 | 202 | | PrintNetworkInformation(networkConfig); |
| | 0 | 203 | | NetworkChanged?.Invoke(this, EventArgs.Empty); |
| | 0 | 204 | | } |
| | | 205 | | finally |
| | | 206 | | { |
| | 0 | 207 | | _eventfire = false; |
| | 0 | 208 | | } |
| | 0 | 209 | | } |
| | | 210 | | |
| | | 211 | | /// <summary> |
| | | 212 | | /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state. |
| | | 213 | | /// </summary> |
| | | 214 | | private void InitializeInterfaces() |
| | 34 | 215 | | { |
| | | 216 | | lock (_initLock) |
| | | 217 | | { |
| | 34 | 218 | | _interfaces = GetInterfacesCore(_logger, IsIPv4Enabled, IsIPv6Enabled).ToList(); |
| | 34 | 219 | | } |
| | 34 | 220 | | } |
| | | 221 | | |
| | | 222 | | /// <summary> |
| | | 223 | | /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state. |
| | | 224 | | /// </summary> |
| | | 225 | | /// <param name="logger">The logger.</param> |
| | | 226 | | /// <param name="isIPv4Enabled">If true evaluates IPV4 type ip addresses.</param> |
| | | 227 | | /// <param name="isIPv6Enabled">If true evaluates IPV6 type ip addresses.</param> |
| | | 228 | | /// <returns>A list of all locally known up addresses and submasks that are to be considered usable.</returns> |
| | | 229 | | public static IReadOnlyList<IPData> GetInterfacesCore(ILogger logger, bool isIPv4Enabled, bool isIPv6Enabled) |
| | | 230 | | { |
| | 34 | 231 | | logger.LogDebug("Refreshing interfaces."); |
| | | 232 | | |
| | 34 | 233 | | var interfaces = new List<IPData>(); |
| | | 234 | | |
| | | 235 | | try |
| | | 236 | | { |
| | 34 | 237 | | var nics = NetworkInterface.GetAllNetworkInterfaces() |
| | 34 | 238 | | .Where(i => i.OperationalStatus == OperationalStatus.Up); |
| | | 239 | | |
| | 204 | 240 | | foreach (NetworkInterface adapter in nics) |
| | | 241 | | { |
| | | 242 | | try |
| | | 243 | | { |
| | 68 | 244 | | var ipProperties = adapter.GetIPProperties(); |
| | | 245 | | |
| | | 246 | | // Populate interface list |
| | 408 | 247 | | foreach (var info in ipProperties.UnicastAddresses) |
| | | 248 | | { |
| | 136 | 249 | | if (isIPv4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork) |
| | | 250 | | { |
| | 68 | 251 | | var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength |
| | 68 | 252 | | { |
| | 68 | 253 | | Index = ipProperties.GetIPv4Properties().Index, |
| | 68 | 254 | | Name = adapter.Name, |
| | 68 | 255 | | SupportsMulticast = adapter.SupportsMulticast |
| | 68 | 256 | | }; |
| | | 257 | | |
| | 68 | 258 | | interfaces.Add(interfaceObject); |
| | | 259 | | } |
| | 68 | 260 | | else if (isIPv6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6) |
| | | 261 | | { |
| | 14 | 262 | | var interfaceObject = new IPData(info.Address, new IPNetwork(info.Address, info.PrefixLength |
| | 14 | 263 | | { |
| | 14 | 264 | | Index = ipProperties.GetIPv6Properties().Index, |
| | 14 | 265 | | Name = adapter.Name, |
| | 14 | 266 | | SupportsMulticast = adapter.SupportsMulticast |
| | 14 | 267 | | }; |
| | | 268 | | |
| | 14 | 269 | | interfaces.Add(interfaceObject); |
| | | 270 | | } |
| | | 271 | | } |
| | 68 | 272 | | } |
| | 0 | 273 | | catch (Exception ex) |
| | | 274 | | { |
| | | 275 | | // Ignore error, and attempt to continue. |
| | 0 | 276 | | logger.LogError(ex, "Error encountered parsing interfaces."); |
| | 0 | 277 | | } |
| | | 278 | | } |
| | 34 | 279 | | } |
| | 0 | 280 | | catch (Exception ex) |
| | | 281 | | { |
| | 0 | 282 | | logger.LogError(ex, "Error obtaining interfaces."); |
| | 0 | 283 | | } |
| | | 284 | | |
| | | 285 | | // If no interfaces are found, fallback to loopback interfaces. |
| | 34 | 286 | | if (interfaces.Count == 0) |
| | | 287 | | { |
| | 0 | 288 | | logger.LogWarning("No interface information available. Using loopback interface(s)."); |
| | | 289 | | |
| | 0 | 290 | | if (isIPv4Enabled) |
| | | 291 | | { |
| | 0 | 292 | | interfaces.Add(new IPData(IPAddress.Loopback, NetworkConstants.IPv4RFC5735Loopback, "lo")); |
| | | 293 | | } |
| | | 294 | | |
| | 0 | 295 | | if (isIPv6Enabled) |
| | | 296 | | { |
| | 0 | 297 | | interfaces.Add(new IPData(IPAddress.IPv6Loopback, NetworkConstants.IPv6RFC4291Loopback, "lo")); |
| | | 298 | | } |
| | | 299 | | } |
| | | 300 | | |
| | 34 | 301 | | logger.LogDebug("Discovered {NumberOfInterfaces} interfaces.", interfaces.Count); |
| | 34 | 302 | | logger.LogDebug("Interfaces addresses: {Addresses}", interfaces.OrderByDescending(s => s.AddressFamily == Addres |
| | 34 | 303 | | return interfaces; |
| | | 304 | | } |
| | | 305 | | |
| | | 306 | | /// <summary> |
| | | 307 | | /// Initializes internal LAN cache. |
| | | 308 | | /// </summary> |
| | | 309 | | [MemberNotNull(nameof(_lanSubnets), nameof(_excludedSubnets))] |
| | | 310 | | private void InitializeLan(NetworkConfiguration config) |
| | 79 | 311 | | { |
| | | 312 | | lock (_initLock) |
| | | 313 | | { |
| | 79 | 314 | | _logger.LogDebug("Refreshing LAN information."); |
| | | 315 | | |
| | | 316 | | // Get configuration options |
| | 79 | 317 | | var subnets = config.LocalNetworkSubnets; |
| | | 318 | | |
| | | 319 | | // If no LAN addresses are specified, all private subnets and Loopback are deemed to be the LAN |
| | 79 | 320 | | if (!NetworkUtils.TryParseToSubnets(subnets, out var lanSubnets, false) || lanSubnets.Count == 0) |
| | | 321 | | { |
| | 45 | 322 | | _logger.LogDebug("Using LAN interface addresses as user provided no LAN details."); |
| | | 323 | | |
| | 45 | 324 | | var fallbackLanSubnets = new List<IPNetwork>(); |
| | 45 | 325 | | if (IsIPv6Enabled) |
| | | 326 | | { |
| | 7 | 327 | | fallbackLanSubnets.Add(NetworkConstants.IPv6RFC4291Loopback); // RFC 4291 (Loopback) |
| | 7 | 328 | | fallbackLanSubnets.Add(NetworkConstants.IPv6RFC4291SiteLocal); // RFC 4291 (Site local) |
| | 7 | 329 | | fallbackLanSubnets.Add(NetworkConstants.IPv6RFC4193UniqueLocal); // RFC 4193 (Unique local) |
| | | 330 | | } |
| | | 331 | | |
| | 45 | 332 | | if (IsIPv4Enabled) |
| | | 333 | | { |
| | 45 | 334 | | fallbackLanSubnets.Add(NetworkConstants.IPv4RFC5735Loopback); // RFC 5735 (Loopback) |
| | 45 | 335 | | fallbackLanSubnets.Add(NetworkConstants.IPv4RFC1918PrivateClassA); // RFC 1918 (private Class A) |
| | 45 | 336 | | fallbackLanSubnets.Add(NetworkConstants.IPv4RFC1918PrivateClassB); // RFC 1918 (private Class B) |
| | 45 | 337 | | fallbackLanSubnets.Add(NetworkConstants.IPv4RFC1918PrivateClassC); // RFC 1918 (private Class C) |
| | | 338 | | } |
| | | 339 | | |
| | 45 | 340 | | _lanSubnets = fallbackLanSubnets; |
| | | 341 | | } |
| | | 342 | | else |
| | | 343 | | { |
| | 34 | 344 | | _lanSubnets = lanSubnets; |
| | | 345 | | } |
| | | 346 | | |
| | 79 | 347 | | _excludedSubnets = NetworkUtils.TryParseToSubnets(subnets, out var excludedSubnets, true) |
| | 79 | 348 | | ? excludedSubnets |
| | 79 | 349 | | : new List<IPNetwork>(); |
| | 79 | 350 | | } |
| | 79 | 351 | | } |
| | | 352 | | |
| | | 353 | | /// <summary> |
| | | 354 | | /// Enforce bind addresses and exclusions on available interfaces. |
| | | 355 | | /// </summary> |
| | | 356 | | private void EnforceBindSettings(NetworkConfiguration config) |
| | 79 | 357 | | { |
| | | 358 | | lock (_initLock) |
| | | 359 | | { |
| | 79 | 360 | | _interfaces = FilterBindSettings(config, _interfaces, IsIPv4Enabled, IsIPv6Enabled).ToList(); |
| | 79 | 361 | | } |
| | 79 | 362 | | } |
| | | 363 | | |
| | | 364 | | /// <summary> |
| | | 365 | | /// Filteres a list of bind addresses and exclusions on available interfaces. |
| | | 366 | | /// </summary> |
| | | 367 | | /// <param name="config">The network config to be filtered by.</param> |
| | | 368 | | /// <param name="interfaces">A list of possible interfaces to be filtered.</param> |
| | | 369 | | /// <param name="isIPv4Enabled">If true evaluates IPV4 type ip addresses.</param> |
| | | 370 | | /// <param name="isIPv6Enabled">If true evaluates IPV6 type ip addresses.</param> |
| | | 371 | | /// <returns>A list of all locally known up addresses and submasks that are to be considered usable.</returns> |
| | | 372 | | public static IReadOnlyList<IPData> FilterBindSettings(NetworkConfiguration config, IList<IPData> interfaces, bool i |
| | | 373 | | { |
| | | 374 | | // Respect explicit bind addresses |
| | 79 | 375 | | var localNetworkAddresses = config.LocalNetworkAddresses; |
| | 79 | 376 | | if (localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses[0])) |
| | | 377 | | { |
| | 12 | 378 | | var bindAddresses = localNetworkAddresses.Select(p => NetworkUtils.TryParseToSubnet(p, out var network) |
| | 12 | 379 | | ? network.Prefix |
| | 12 | 380 | | : (interfaces.Where(x => x.Name.Equals(p, StringComparison.OrdinalIgnoreCase)) |
| | 12 | 381 | | .Select(x => x.Address) |
| | 12 | 382 | | .FirstOrDefault() ?? IPAddress.None)) |
| | 12 | 383 | | .Where(x => x != IPAddress.None) |
| | 12 | 384 | | .ToHashSet(); |
| | 12 | 385 | | interfaces = interfaces.Where(x => bindAddresses.Contains(x.Address)).ToList(); |
| | | 386 | | |
| | 12 | 387 | | if (bindAddresses.Contains(IPAddress.Loopback) && !interfaces.Any(i => i.Address.Equals(IPAddress.Loopback)) |
| | | 388 | | { |
| | 0 | 389 | | interfaces.Add(new IPData(IPAddress.Loopback, NetworkConstants.IPv4RFC5735Loopback, "lo")); |
| | | 390 | | } |
| | | 391 | | |
| | 12 | 392 | | if (bindAddresses.Contains(IPAddress.IPv6Loopback) && !interfaces.Any(i => i.Address.Equals(IPAddress.IPv6Lo |
| | | 393 | | { |
| | 0 | 394 | | interfaces.Add(new IPData(IPAddress.IPv6Loopback, NetworkConstants.IPv6RFC4291Loopback, "lo")); |
| | | 395 | | } |
| | | 396 | | } |
| | | 397 | | |
| | | 398 | | // Remove all interfaces matching any virtual machine interface prefix |
| | 79 | 399 | | if (config.IgnoreVirtualInterfaces) |
| | | 400 | | { |
| | | 401 | | // Remove potentially existing * and split config string into prefixes |
| | 79 | 402 | | var virtualInterfacePrefixes = config.VirtualInterfaceNames |
| | 79 | 403 | | .Select(i => i.Replace("*", string.Empty, StringComparison.OrdinalIgnoreCase)); |
| | | 404 | | |
| | | 405 | | // Check all interfaces for matches against the prefixes and remove them |
| | 79 | 406 | | if (interfaces.Count > 0) |
| | | 407 | | { |
| | 316 | 408 | | foreach (var virtualInterfacePrefix in virtualInterfacePrefixes) |
| | | 409 | | { |
| | 79 | 410 | | interfaces.RemoveAll(x => x.Name.StartsWith(virtualInterfacePrefix, StringComparison.OrdinalIgnoreCa |
| | | 411 | | } |
| | | 412 | | } |
| | | 413 | | } |
| | | 414 | | |
| | | 415 | | // Remove all IPv4 interfaces if IPv4 is disabled |
| | 79 | 416 | | if (!isIPv4Enabled) |
| | | 417 | | { |
| | 0 | 418 | | interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetwork); |
| | | 419 | | } |
| | | 420 | | |
| | | 421 | | // Remove all IPv6 interfaces if IPv6 is disabled |
| | 79 | 422 | | if (!isIPv6Enabled) |
| | | 423 | | { |
| | 55 | 424 | | interfaces.RemoveAll(x => x.AddressFamily == AddressFamily.InterNetworkV6); |
| | | 425 | | } |
| | | 426 | | |
| | | 427 | | // Users may have complex networking configuration that multiple interfaces sharing the same IP address |
| | | 428 | | // Only return one IP for binding, and let the OS handle the rest |
| | 79 | 429 | | return interfaces.DistinctBy(iface => iface.Address).ToList(); |
| | | 430 | | } |
| | | 431 | | |
| | | 432 | | /// <summary> |
| | | 433 | | /// Initializes the remote address values. |
| | | 434 | | /// </summary> |
| | | 435 | | private void InitializeRemote(NetworkConfiguration config) |
| | 79 | 436 | | { |
| | | 437 | | lock (_initLock) |
| | | 438 | | { |
| | | 439 | | // Parse config values into filter collection |
| | 79 | 440 | | var remoteIPFilter = config.RemoteIPFilter; |
| | 79 | 441 | | if (remoteIPFilter.Length != 0 && !string.IsNullOrWhiteSpace(remoteIPFilter[0])) |
| | | 442 | | { |
| | | 443 | | // Parse all IPs with netmask to a subnet |
| | 6 | 444 | | var remoteAddressFilter = new List<IPNetwork>(); |
| | 6 | 445 | | var remoteFilteredSubnets = remoteIPFilter.Where(x => x.Contains('/', StringComparison.OrdinalIgnoreCase |
| | 6 | 446 | | if (NetworkUtils.TryParseToSubnets(remoteFilteredSubnets, out var remoteAddressFilterResult, false)) |
| | | 447 | | { |
| | 0 | 448 | | remoteAddressFilter = remoteAddressFilterResult.ToList(); |
| | | 449 | | } |
| | | 450 | | |
| | | 451 | | // Parse everything else as an IP and construct subnet with a single IP |
| | 6 | 452 | | var remoteFilteredIPs = remoteIPFilter.Where(x => !x.Contains('/', StringComparison.OrdinalIgnoreCase)); |
| | 28 | 453 | | foreach (var ip in remoteFilteredIPs) |
| | | 454 | | { |
| | 8 | 455 | | if (IPAddress.TryParse(ip, out var ipp)) |
| | | 456 | | { |
| | 8 | 457 | | remoteAddressFilter.Add(new IPNetwork(ipp, ipp.AddressFamily == AddressFamily.InterNetwork ? Net |
| | | 458 | | } |
| | | 459 | | } |
| | | 460 | | |
| | 6 | 461 | | _remoteAddressFilter = remoteAddressFilter; |
| | | 462 | | } |
| | 79 | 463 | | } |
| | 79 | 464 | | } |
| | | 465 | | |
| | | 466 | | /// <summary> |
| | | 467 | | /// Parses the user defined overrides into the dictionary object. |
| | | 468 | | /// Overrides are the equivalent of localised publishedServerUrl, enabling |
| | | 469 | | /// different addresses to be advertised over different subnets. |
| | | 470 | | /// format is subnet=ipaddress|host|uri |
| | | 471 | | /// when subnet = 0.0.0.0, any external address matches. |
| | | 472 | | /// </summary> |
| | | 473 | | private void InitializeOverrides(NetworkConfiguration config) |
| | 79 | 474 | | { |
| | | 475 | | lock (_initLock) |
| | | 476 | | { |
| | 79 | 477 | | var publishedServerUrls = new List<PublishedServerUriOverride>(); |
| | | 478 | | |
| | | 479 | | // Prefer startup configuration. |
| | 79 | 480 | | var startupOverrideKey = _startupConfig[AddressOverrideKey]; |
| | 79 | 481 | | if (!string.IsNullOrEmpty(startupOverrideKey)) |
| | | 482 | | { |
| | 0 | 483 | | publishedServerUrls.Add( |
| | 0 | 484 | | new PublishedServerUriOverride( |
| | 0 | 485 | | new IPData(IPAddress.Any, NetworkConstants.IPv4Any), |
| | 0 | 486 | | startupOverrideKey, |
| | 0 | 487 | | true, |
| | 0 | 488 | | true)); |
| | 0 | 489 | | publishedServerUrls.Add( |
| | 0 | 490 | | new PublishedServerUriOverride( |
| | 0 | 491 | | new IPData(IPAddress.IPv6Any, NetworkConstants.IPv6Any), |
| | 0 | 492 | | startupOverrideKey, |
| | 0 | 493 | | true, |
| | 0 | 494 | | true)); |
| | 0 | 495 | | _publishedServerUrls = publishedServerUrls; |
| | 0 | 496 | | return; |
| | | 497 | | } |
| | | 498 | | |
| | 79 | 499 | | var overrides = config.PublishedServerUriBySubnet; |
| | 172 | 500 | | foreach (var entry in overrides) |
| | | 501 | | { |
| | 8 | 502 | | var parts = entry.Split('='); |
| | 8 | 503 | | if (parts.Length != 2) |
| | | 504 | | { |
| | 0 | 505 | | _logger.LogError("Unable to parse bind override: {Entry}", entry); |
| | 0 | 506 | | return; |
| | | 507 | | } |
| | | 508 | | |
| | 8 | 509 | | var replacement = parts[1].Trim(); |
| | 8 | 510 | | var identifier = parts[0]; |
| | 8 | 511 | | if (string.Equals(identifier, "all", StringComparison.OrdinalIgnoreCase)) |
| | | 512 | | { |
| | | 513 | | // Drop any other overrides in case an "all" override exists |
| | 2 | 514 | | publishedServerUrls.Clear(); |
| | 2 | 515 | | publishedServerUrls.Add( |
| | 2 | 516 | | new PublishedServerUriOverride( |
| | 2 | 517 | | new IPData(IPAddress.Any, NetworkConstants.IPv4Any), |
| | 2 | 518 | | replacement, |
| | 2 | 519 | | true, |
| | 2 | 520 | | true)); |
| | 2 | 521 | | publishedServerUrls.Add( |
| | 2 | 522 | | new PublishedServerUriOverride( |
| | 2 | 523 | | new IPData(IPAddress.IPv6Any, NetworkConstants.IPv6Any), |
| | 2 | 524 | | replacement, |
| | 2 | 525 | | true, |
| | 2 | 526 | | true)); |
| | 2 | 527 | | break; |
| | | 528 | | } |
| | 6 | 529 | | else if (string.Equals(identifier, "external", StringComparison.OrdinalIgnoreCase)) |
| | | 530 | | { |
| | 4 | 531 | | publishedServerUrls.Add( |
| | 4 | 532 | | new PublishedServerUriOverride( |
| | 4 | 533 | | new IPData(IPAddress.Any, NetworkConstants.IPv4Any), |
| | 4 | 534 | | replacement, |
| | 4 | 535 | | false, |
| | 4 | 536 | | true)); |
| | 4 | 537 | | publishedServerUrls.Add( |
| | 4 | 538 | | new PublishedServerUriOverride( |
| | 4 | 539 | | new IPData(IPAddress.IPv6Any, NetworkConstants.IPv6Any), |
| | 4 | 540 | | replacement, |
| | 4 | 541 | | false, |
| | 4 | 542 | | true)); |
| | | 543 | | } |
| | 2 | 544 | | else if (string.Equals(identifier, "internal", StringComparison.OrdinalIgnoreCase)) |
| | | 545 | | { |
| | 0 | 546 | | foreach (var lan in _lanSubnets) |
| | | 547 | | { |
| | 0 | 548 | | var lanPrefix = lan.Prefix; |
| | 0 | 549 | | publishedServerUrls.Add( |
| | 0 | 550 | | new PublishedServerUriOverride( |
| | 0 | 551 | | new IPData(lanPrefix, new IPNetwork(lanPrefix, lan.PrefixLength)), |
| | 0 | 552 | | replacement, |
| | 0 | 553 | | true, |
| | 0 | 554 | | false)); |
| | | 555 | | } |
| | | 556 | | } |
| | 2 | 557 | | else if (NetworkUtils.TryParseToSubnet(identifier, out var result) && result is not null) |
| | | 558 | | { |
| | 1 | 559 | | var data = new IPData(result.Prefix, result); |
| | 1 | 560 | | publishedServerUrls.Add( |
| | 1 | 561 | | new PublishedServerUriOverride( |
| | 1 | 562 | | data, |
| | 1 | 563 | | replacement, |
| | 1 | 564 | | true, |
| | 1 | 565 | | true)); |
| | | 566 | | } |
| | 1 | 567 | | else if (TryParseInterface(identifier, out var ifaces)) |
| | | 568 | | { |
| | 4 | 569 | | foreach (var iface in ifaces) |
| | | 570 | | { |
| | 1 | 571 | | publishedServerUrls.Add( |
| | 1 | 572 | | new PublishedServerUriOverride( |
| | 1 | 573 | | iface, |
| | 1 | 574 | | replacement, |
| | 1 | 575 | | true, |
| | 1 | 576 | | true)); |
| | | 577 | | } |
| | | 578 | | } |
| | | 579 | | else |
| | | 580 | | { |
| | 0 | 581 | | _logger.LogError("Unable to parse bind override: {Entry}", entry); |
| | | 582 | | } |
| | | 583 | | } |
| | | 584 | | |
| | 79 | 585 | | _publishedServerUrls = publishedServerUrls; |
| | 79 | 586 | | } |
| | 79 | 587 | | } |
| | | 588 | | |
| | | 589 | | private void ConfigurationUpdated(object? sender, ConfigurationUpdateEventArgs evt) |
| | | 590 | | { |
| | 22 | 591 | | if (evt.Key.Equals(NetworkConfigurationStore.StoreKey, StringComparison.Ordinal)) |
| | | 592 | | { |
| | 0 | 593 | | UpdateSettings((NetworkConfiguration)evt.NewConfiguration); |
| | | 594 | | } |
| | 22 | 595 | | } |
| | | 596 | | |
| | | 597 | | /// <summary> |
| | | 598 | | /// Reloads all settings and re-Initializes the instance. |
| | | 599 | | /// </summary> |
| | | 600 | | /// <param name="configuration">The <see cref="NetworkConfiguration"/> to use.</param> |
| | | 601 | | [MemberNotNull(nameof(_lanSubnets), nameof(_excludedSubnets))] |
| | | 602 | | public void UpdateSettings(object configuration) |
| | | 603 | | { |
| | 79 | 604 | | ArgumentNullException.ThrowIfNull(configuration); |
| | | 605 | | |
| | 79 | 606 | | var config = (NetworkConfiguration)configuration; |
| | 79 | 607 | | HappyEyeballs.HttpClientExtension.UseIPv6 = config.EnableIPv6; |
| | | 608 | | |
| | 79 | 609 | | InitializeLan(config); |
| | 79 | 610 | | InitializeRemote(config); |
| | | 611 | | |
| | 79 | 612 | | if (string.IsNullOrEmpty(MockNetworkSettings)) |
| | | 613 | | { |
| | 34 | 614 | | InitializeInterfaces(); |
| | | 615 | | } |
| | | 616 | | else // Used in testing only. |
| | | 617 | | { |
| | | 618 | | // Format is <IPAddress>,<Index>,<Name>: <next interface>. Set index to -ve to simulate a gateway. |
| | 45 | 619 | | var interfaceList = MockNetworkSettings.Split('|'); |
| | 45 | 620 | | var interfaces = new List<IPData>(); |
| | 272 | 621 | | foreach (var details in interfaceList) |
| | | 622 | | { |
| | 91 | 623 | | var parts = details.Split(','); |
| | 91 | 624 | | if (NetworkUtils.TryParseToSubnet(parts[0], out var subnet)) |
| | | 625 | | { |
| | 91 | 626 | | var address = subnet.Prefix; |
| | 91 | 627 | | var index = int.Parse(parts[1], CultureInfo.InvariantCulture); |
| | 91 | 628 | | if (address.AddressFamily == AddressFamily.InterNetwork || address.AddressFamily == AddressFamily.In |
| | | 629 | | { |
| | 91 | 630 | | var data = new IPData(address, subnet, parts[2]) |
| | 91 | 631 | | { |
| | 91 | 632 | | Index = index |
| | 91 | 633 | | }; |
| | 91 | 634 | | interfaces.Add(data); |
| | | 635 | | } |
| | | 636 | | } |
| | | 637 | | else |
| | | 638 | | { |
| | 0 | 639 | | _logger.LogWarning("Could not parse mock interface settings: {Part}", details); |
| | | 640 | | } |
| | | 641 | | } |
| | | 642 | | |
| | 45 | 643 | | _interfaces = interfaces; |
| | | 644 | | } |
| | | 645 | | |
| | 79 | 646 | | EnforceBindSettings(config); |
| | 79 | 647 | | InitializeOverrides(config); |
| | | 648 | | |
| | 79 | 649 | | PrintNetworkInformation(config, false); |
| | 79 | 650 | | } |
| | | 651 | | |
| | | 652 | | /// <summary> |
| | | 653 | | /// Protected implementation of Dispose pattern. |
| | | 654 | | /// </summary> |
| | | 655 | | /// <param name="disposing"><c>True</c> to dispose the managed state.</param> |
| | | 656 | | protected virtual void Dispose(bool disposing) |
| | | 657 | | { |
| | 58 | 658 | | if (!_disposed) |
| | | 659 | | { |
| | 58 | 660 | | if (disposing) |
| | | 661 | | { |
| | 58 | 662 | | _configurationManager.NamedConfigurationUpdated -= ConfigurationUpdated; |
| | 58 | 663 | | NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged; |
| | 58 | 664 | | NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged; |
| | | 665 | | } |
| | | 666 | | |
| | 58 | 667 | | _disposed = true; |
| | | 668 | | } |
| | 58 | 669 | | } |
| | | 670 | | |
| | | 671 | | /// <inheritdoc/> |
| | | 672 | | public bool TryParseInterface(string intf, [NotNullWhen(true)] out IReadOnlyList<IPData>? result) |
| | | 673 | | { |
| | 15 | 674 | | if (string.IsNullOrEmpty(intf) |
| | 15 | 675 | | || _interfaces is null |
| | 15 | 676 | | || _interfaces.Count == 0) |
| | | 677 | | { |
| | 0 | 678 | | result = null; |
| | 0 | 679 | | return false; |
| | | 680 | | } |
| | | 681 | | |
| | | 682 | | // Match all interfaces starting with names starting with token |
| | 15 | 683 | | result = _interfaces |
| | 15 | 684 | | .Where(i => i.Name.Equals(intf, StringComparison.OrdinalIgnoreCase) |
| | 15 | 685 | | && ((IsIPv4Enabled && i.Address.AddressFamily == AddressFamily.InterNetwork) |
| | 15 | 686 | | || (IsIPv6Enabled && i.Address.AddressFamily == AddressFamily.InterNetworkV6))) |
| | 15 | 687 | | .OrderBy(x => x.Index) |
| | 15 | 688 | | .ToArray(); |
| | 15 | 689 | | return result.Count > 0; |
| | | 690 | | } |
| | | 691 | | |
| | | 692 | | /// <inheritdoc/> |
| | | 693 | | public RemoteAccessPolicyResult ShouldAllowServerAccess(IPAddress remoteIP) |
| | | 694 | | { |
| | 9 | 695 | | var config = _configurationManager.GetNetworkConfiguration(); |
| | 9 | 696 | | if (IsInLocalNetwork(remoteIP)) |
| | | 697 | | { |
| | 1 | 698 | | return RemoteAccessPolicyResult.Allow; |
| | | 699 | | } |
| | | 700 | | |
| | 8 | 701 | | if (!config.EnableRemoteAccess) |
| | | 702 | | { |
| | | 703 | | // Remote not enabled. So everyone should be LAN. |
| | 2 | 704 | | return RemoteAccessPolicyResult.RejectDueToRemoteAccessDisabled; |
| | | 705 | | } |
| | | 706 | | |
| | 6 | 707 | | if (!_remoteAddressFilter.Any()) |
| | | 708 | | { |
| | | 709 | | // No filter on remote addresses, allow any of them. |
| | 2 | 710 | | return RemoteAccessPolicyResult.Allow; |
| | | 711 | | } |
| | | 712 | | |
| | | 713 | | // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remot |
| | | 714 | | // If left blank, all remote addresses will be allowed. |
| | | 715 | | |
| | | 716 | | // remoteAddressFilter is a whitelist or blacklist. |
| | 4 | 717 | | var anyMatches = _remoteAddressFilter.Any(remoteNetwork => NetworkUtils.SubnetContainsAddress(remoteNetwork, rem |
| | 4 | 718 | | if (config.IsRemoteIPFilterBlacklist) |
| | | 719 | | { |
| | 2 | 720 | | return anyMatches |
| | 2 | 721 | | ? RemoteAccessPolicyResult.RejectDueToIPBlocklist |
| | 2 | 722 | | : RemoteAccessPolicyResult.Allow; |
| | | 723 | | } |
| | | 724 | | |
| | | 725 | | // Allow-list |
| | 2 | 726 | | return anyMatches |
| | 2 | 727 | | ? RemoteAccessPolicyResult.Allow |
| | 2 | 728 | | : RemoteAccessPolicyResult.RejectDueToNotAllowlistedRemoteIP; |
| | | 729 | | } |
| | | 730 | | |
| | | 731 | | /// <inheritdoc/> |
| | | 732 | | public IReadOnlyList<IPData> GetLoopbacks() |
| | | 733 | | { |
| | 0 | 734 | | if (!IsIPv4Enabled && !IsIPv6Enabled) |
| | | 735 | | { |
| | 0 | 736 | | return Array.Empty<IPData>(); |
| | | 737 | | } |
| | | 738 | | |
| | 0 | 739 | | var loopbackNetworks = new List<IPData>(); |
| | 0 | 740 | | if (IsIPv4Enabled) |
| | | 741 | | { |
| | 0 | 742 | | loopbackNetworks.Add(new IPData(IPAddress.Loopback, NetworkConstants.IPv4RFC5735Loopback, "lo")); |
| | | 743 | | } |
| | | 744 | | |
| | 0 | 745 | | if (IsIPv6Enabled) |
| | | 746 | | { |
| | 0 | 747 | | loopbackNetworks.Add(new IPData(IPAddress.IPv6Loopback, NetworkConstants.IPv6RFC4291Loopback, "lo")); |
| | | 748 | | } |
| | | 749 | | |
| | 0 | 750 | | return loopbackNetworks; |
| | | 751 | | } |
| | | 752 | | |
| | | 753 | | /// <inheritdoc/> |
| | | 754 | | public IReadOnlyList<IPData> GetAllBindInterfaces(bool individualInterfaces = false) |
| | | 755 | | { |
| | 21 | 756 | | return NetworkManager.GetAllBindInterfaces(individualInterfaces, _configurationManager, _interfaces, IsIPv4Enabl |
| | | 757 | | } |
| | | 758 | | |
| | | 759 | | /// <summary> |
| | | 760 | | /// Reads the jellyfin configuration of the configuration manager and produces a list of interfaces that should be b |
| | | 761 | | /// </summary> |
| | | 762 | | /// <param name="individualInterfaces">Defines that only known interfaces should be used.</param> |
| | | 763 | | /// <param name="configurationManager">The ConfigurationManager.</param> |
| | | 764 | | /// <param name="knownInterfaces">The known interfaces that gets returned if possible or instructed.</param> |
| | | 765 | | /// <param name="readIpv4">Include IPV4 type interfaces.</param> |
| | | 766 | | /// <param name="readIpv6">Include IPV6 type interfaces.</param> |
| | | 767 | | /// <returns>A list of ip address of which jellyfin should bind to.</returns> |
| | | 768 | | public static IReadOnlyList<IPData> GetAllBindInterfaces( |
| | | 769 | | bool individualInterfaces, |
| | | 770 | | IConfigurationManager configurationManager, |
| | | 771 | | IReadOnlyList<IPData> knownInterfaces, |
| | | 772 | | bool readIpv4, |
| | | 773 | | bool readIpv6) |
| | | 774 | | { |
| | 21 | 775 | | var config = configurationManager.GetNetworkConfiguration(); |
| | 21 | 776 | | var localNetworkAddresses = config.LocalNetworkAddresses; |
| | 21 | 777 | | if ((localNetworkAddresses.Length > 0 && !string.IsNullOrWhiteSpace(localNetworkAddresses[0]) && knownInterfaces |
| | | 778 | | { |
| | 0 | 779 | | return knownInterfaces; |
| | | 780 | | } |
| | | 781 | | |
| | | 782 | | // No bind address and no exclusions, so listen on all interfaces. |
| | 21 | 783 | | var result = new List<IPData>(); |
| | 21 | 784 | | if (readIpv4 && readIpv6) |
| | | 785 | | { |
| | | 786 | | // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any by default |
| | 0 | 787 | | result.Add(new IPData(IPAddress.IPv6Any, NetworkConstants.IPv6Any)); |
| | | 788 | | } |
| | 21 | 789 | | else if (readIpv4) |
| | | 790 | | { |
| | 21 | 791 | | result.Add(new IPData(IPAddress.Any, NetworkConstants.IPv4Any)); |
| | | 792 | | } |
| | 0 | 793 | | else if (readIpv6) |
| | | 794 | | { |
| | | 795 | | // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too. |
| | 0 | 796 | | foreach (var iface in knownInterfaces) |
| | | 797 | | { |
| | 0 | 798 | | if (iface.AddressFamily == AddressFamily.InterNetworkV6) |
| | | 799 | | { |
| | 0 | 800 | | result.Add(iface); |
| | | 801 | | } |
| | | 802 | | } |
| | | 803 | | } |
| | | 804 | | |
| | 21 | 805 | | return result; |
| | | 806 | | } |
| | | 807 | | |
| | | 808 | | /// <inheritdoc/> |
| | | 809 | | public string GetBindAddress(string source, out int? port) |
| | | 810 | | { |
| | 23 | 811 | | if (!NetworkUtils.TryParseHost(source, out var addresses, IsIPv4Enabled, IsIPv6Enabled)) |
| | | 812 | | { |
| | 4 | 813 | | addresses = Array.Empty<IPAddress>(); |
| | | 814 | | } |
| | | 815 | | |
| | 23 | 816 | | var result = GetBindAddress(addresses.FirstOrDefault(), out port); |
| | 23 | 817 | | return result; |
| | | 818 | | } |
| | | 819 | | |
| | | 820 | | /// <inheritdoc/> |
| | | 821 | | public string GetBindAddress(HttpRequest source, out int? port) |
| | | 822 | | { |
| | 0 | 823 | | var result = GetBindAddress(source.Host.Host, out port); |
| | 0 | 824 | | port ??= source.Host.Port; |
| | | 825 | | |
| | 0 | 826 | | return result; |
| | | 827 | | } |
| | | 828 | | |
| | | 829 | | /// <inheritdoc/> |
| | | 830 | | public string GetBindAddress(IPAddress? source, out int? port, bool skipOverrides = false) |
| | | 831 | | { |
| | 23 | 832 | | port = null; |
| | | 833 | | |
| | | 834 | | string result; |
| | | 835 | | |
| | 23 | 836 | | if (source is not null) |
| | | 837 | | { |
| | 19 | 838 | | if (IsIPv4Enabled && !IsIPv6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6) |
| | | 839 | | { |
| | 0 | 840 | | _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interfa |
| | | 841 | | } |
| | | 842 | | |
| | 19 | 843 | | if (!IsIPv4Enabled && IsIPv6Enabled && source.AddressFamily == AddressFamily.InterNetwork) |
| | | 844 | | { |
| | 0 | 845 | | _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interfa |
| | | 846 | | } |
| | | 847 | | |
| | 19 | 848 | | bool isExternal = !IsInLocalNetwork(source); |
| | 19 | 849 | | _logger.LogDebug("Trying to get bind address for source {Source} - External: {IsExternal}", source, isExtern |
| | | 850 | | |
| | 19 | 851 | | if (!skipOverrides && MatchesPublishedServerUrl(source, isExternal, out result)) |
| | | 852 | | { |
| | 6 | 853 | | return result; |
| | | 854 | | } |
| | | 855 | | |
| | | 856 | | // No preference given, so move on to bind addresses. |
| | 13 | 857 | | if (MatchesBindInterface(source, isExternal, out result)) |
| | | 858 | | { |
| | 11 | 859 | | return result; |
| | | 860 | | } |
| | | 861 | | |
| | 2 | 862 | | if (isExternal && MatchesExternalInterface(source, out result)) |
| | | 863 | | { |
| | 0 | 864 | | return result; |
| | | 865 | | } |
| | | 866 | | } |
| | | 867 | | |
| | | 868 | | // Get the first LAN interface address that's not excluded and not a loopback address. |
| | | 869 | | // Get all available interfaces, prefer local interfaces |
| | 6 | 870 | | var availableInterfaces = _interfaces.Where(x => !IPAddress.IsLoopback(x.Address)) |
| | 6 | 871 | | .OrderByDescending(x => IsInLocalNetwork(x.Address)) |
| | 6 | 872 | | .ThenBy(x => x.Index) |
| | 6 | 873 | | .ToList(); |
| | | 874 | | |
| | 6 | 875 | | if (availableInterfaces.Count == 0) |
| | | 876 | | { |
| | | 877 | | // There isn't any others, so we'll use the loopback. |
| | 0 | 878 | | result = IsIPv4Enabled && !IsIPv6Enabled ? "127.0.0.1" : "::1"; |
| | 0 | 879 | | _logger.LogWarning("{Source}: Only loopback {Result} returned, using that as bind address.", source, result) |
| | 0 | 880 | | return result; |
| | | 881 | | } |
| | | 882 | | |
| | | 883 | | // If no source address is given, use the preferred (first) interface |
| | 6 | 884 | | if (source is null) |
| | | 885 | | { |
| | 4 | 886 | | result = NetworkUtils.FormatIPString(availableInterfaces.First().Address); |
| | 4 | 887 | | _logger.LogDebug("{Source}: Using first internal interface as bind address: {Result}", source, result); |
| | 4 | 888 | | return result; |
| | | 889 | | } |
| | | 890 | | |
| | | 891 | | // Does the request originate in one of the interface subnets? |
| | | 892 | | // (For systems with multiple internal network cards, and multiple subnets) |
| | 8 | 893 | | foreach (var intf in availableInterfaces) |
| | | 894 | | { |
| | 2 | 895 | | if (NetworkUtils.SubnetContainsAddress(intf.Subnet, source)) |
| | | 896 | | { |
| | 0 | 897 | | result = NetworkUtils.FormatIPString(intf.Address); |
| | 0 | 898 | | _logger.LogDebug("{Source}: Found interface with matching subnet, using it as bind address: {Result}", s |
| | 0 | 899 | | return result; |
| | | 900 | | } |
| | | 901 | | } |
| | | 902 | | |
| | | 903 | | // Fallback to first available interface |
| | 2 | 904 | | result = NetworkUtils.FormatIPString(availableInterfaces[0].Address); |
| | 2 | 905 | | _logger.LogDebug("{Source}: No matching interfaces found, using preferred interface as bind address: {Result}", |
| | 2 | 906 | | return result; |
| | 0 | 907 | | } |
| | | 908 | | |
| | | 909 | | /// <inheritdoc/> |
| | | 910 | | public IReadOnlyList<IPData> GetInternalBindAddresses() |
| | | 911 | | { |
| | | 912 | | // Select all local bind addresses |
| | 6 | 913 | | return _interfaces.Where(x => IsInLocalNetwork(x.Address)) |
| | 6 | 914 | | .OrderBy(x => x.Index) |
| | 6 | 915 | | .ToList(); |
| | | 916 | | } |
| | | 917 | | |
| | | 918 | | /// <inheritdoc/> |
| | | 919 | | public bool IsInLocalNetwork(string address) |
| | | 920 | | { |
| | 0 | 921 | | if (NetworkUtils.TryParseToSubnet(address, out var subnet)) |
| | | 922 | | { |
| | 0 | 923 | | return IsInLocalNetwork(subnet.Prefix); |
| | | 924 | | } |
| | | 925 | | |
| | 0 | 926 | | return NetworkUtils.TryParseHost(address, out var addresses, IsIPv4Enabled, IsIPv6Enabled) |
| | 0 | 927 | | && addresses.Any(IsInLocalNetwork); |
| | | 928 | | } |
| | | 929 | | |
| | | 930 | | /// <summary> |
| | | 931 | | /// Get if the IPAddress is Link-local. |
| | | 932 | | /// </summary> |
| | | 933 | | /// <param name="address">The IP Address.</param> |
| | | 934 | | /// <returns>Bool indicates if the address is link-local.</returns> |
| | | 935 | | public bool IsLinkLocalAddress(IPAddress address) |
| | | 936 | | { |
| | 4 | 937 | | ArgumentNullException.ThrowIfNull(address); |
| | 4 | 938 | | return NetworkConstants.IPv4RFC3927LinkLocal.Contains(address) || address.IsIPv6LinkLocal; |
| | | 939 | | } |
| | | 940 | | |
| | | 941 | | /// <inheritdoc/> |
| | | 942 | | public bool IsInLocalNetwork(IPAddress address) |
| | | 943 | | { |
| | 162 | 944 | | ArgumentNullException.ThrowIfNull(address); |
| | | 945 | | |
| | | 946 | | // Map IPv6 mapped IPv4 back to IPv4 (happens if Kestrel runs in dual-socket mode) |
| | 162 | 947 | | if (address.IsIPv4MappedToIPv6) |
| | | 948 | | { |
| | 0 | 949 | | address = address.MapToIPv4(); |
| | | 950 | | } |
| | | 951 | | |
| | 162 | 952 | | if ((TrustAllIPv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6) |
| | 162 | 953 | | || IPAddress.IsLoopback(address)) |
| | | 954 | | { |
| | 86 | 955 | | return true; |
| | | 956 | | } |
| | | 957 | | |
| | | 958 | | // As private addresses can be redefined by Configuration.LocalNetworkAddresses |
| | 76 | 959 | | return CheckIfLanAndNotExcluded(address); |
| | | 960 | | } |
| | | 961 | | |
| | | 962 | | /// <summary> |
| | | 963 | | /// Check if the address is in the LAN and not excluded. |
| | | 964 | | /// </summary> |
| | | 965 | | /// <param name="address">The IP address to check. The caller should make sure this is not an IPv4MappedToIPv6 addre |
| | | 966 | | /// <returns>Boolean indicates whether the address is in LAN.</returns> |
| | | 967 | | private bool CheckIfLanAndNotExcluded(IPAddress address) |
| | | 968 | | { |
| | 416 | 969 | | foreach (var lanSubnet in _lanSubnets) |
| | | 970 | | { |
| | 151 | 971 | | if (lanSubnet.Contains(address)) |
| | | 972 | | { |
| | 82 | 973 | | foreach (var excludedSubnet in _excludedSubnets) |
| | | 974 | | { |
| | 4 | 975 | | if (excludedSubnet.Contains(address)) |
| | | 976 | | { |
| | 2 | 977 | | return false; |
| | | 978 | | } |
| | | 979 | | } |
| | | 980 | | |
| | 36 | 981 | | return true; |
| | | 982 | | } |
| | | 983 | | } |
| | | 984 | | |
| | 38 | 985 | | return false; |
| | 38 | 986 | | } |
| | | 987 | | |
| | | 988 | | /// <summary> |
| | | 989 | | /// Attempts to match the source against the published server URL overrides. |
| | | 990 | | /// </summary> |
| | | 991 | | /// <param name="source">IP source address to use.</param> |
| | | 992 | | /// <param name="isInExternalSubnet">True if the source is in an external subnet.</param> |
| | | 993 | | /// <param name="bindPreference">The published server URL that matches the source address.</param> |
| | | 994 | | /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> |
| | | 995 | | private bool MatchesPublishedServerUrl(IPAddress source, bool isInExternalSubnet, out string bindPreference) |
| | | 996 | | { |
| | 19 | 997 | | bindPreference = string.Empty; |
| | 19 | 998 | | int? port = null; |
| | | 999 | | |
| | | 1000 | | // Only consider subnets including the source IP, preferring specific overrides |
| | | 1001 | | List<PublishedServerUriOverride> validPublishedServerUrls; |
| | 19 | 1002 | | if (!isInExternalSubnet) |
| | | 1003 | | { |
| | | 1004 | | // Only use matching internal subnets |
| | | 1005 | | // Prefer more specific (bigger subnet prefix) overrides |
| | 10 | 1006 | | validPublishedServerUrls = _publishedServerUrls.Where(x => x.IsInternalOverride && NetworkUtils.SubnetContai |
| | 10 | 1007 | | .OrderByDescending(x => x.Data.Subnet.PrefixLength) |
| | 10 | 1008 | | .ToList(); |
| | | 1009 | | } |
| | | 1010 | | else |
| | | 1011 | | { |
| | | 1012 | | // Only use matching external subnets |
| | | 1013 | | // Prefer more specific (bigger subnet prefix) overrides |
| | 9 | 1014 | | validPublishedServerUrls = _publishedServerUrls.Where(x => x.IsExternalOverride && NetworkUtils.SubnetContai |
| | 9 | 1015 | | .OrderByDescending(x => x.Data.Subnet.PrefixLength) |
| | 9 | 1016 | | .ToList(); |
| | | 1017 | | } |
| | | 1018 | | |
| | 44 | 1019 | | foreach (var data in validPublishedServerUrls) |
| | | 1020 | | { |
| | | 1021 | | // Get interface matching override subnet |
| | 6 | 1022 | | var intf = _interfaces.OrderBy(x => x.Index).FirstOrDefault(x => NetworkUtils.SubnetContainsAddress(data.Dat |
| | | 1023 | | |
| | 6 | 1024 | | if (intf?.Address is not null |
| | 6 | 1025 | | || (data.Data.AddressFamily == AddressFamily.InterNetwork && data.Data.Address.Equals(IPAddress.Any)) |
| | 6 | 1026 | | || (data.Data.AddressFamily == AddressFamily.InterNetworkV6 && data.Data.Address.Equals(IPAddress.IPv6An |
| | | 1027 | | { |
| | | 1028 | | // If matching interface is found, use override |
| | 6 | 1029 | | bindPreference = data.OverrideUri; |
| | 6 | 1030 | | break; |
| | | 1031 | | } |
| | | 1032 | | } |
| | | 1033 | | |
| | 19 | 1034 | | if (string.IsNullOrEmpty(bindPreference)) |
| | | 1035 | | { |
| | 13 | 1036 | | _logger.LogDebug("{Source}: No matching bind address override found", source); |
| | 13 | 1037 | | return false; |
| | | 1038 | | } |
| | | 1039 | | |
| | | 1040 | | // Handle override specifying port |
| | 6 | 1041 | | var parts = bindPreference.Split(':'); |
| | 6 | 1042 | | if (parts.Length > 1) |
| | | 1043 | | { |
| | 5 | 1044 | | if (int.TryParse(parts[1], out int p)) |
| | | 1045 | | { |
| | 0 | 1046 | | bindPreference = parts[0]; |
| | 0 | 1047 | | port = p; |
| | 0 | 1048 | | _logger.LogDebug("{Source}: Matching bind address override found: {Address}:{Port}", source, bindPrefere |
| | 0 | 1049 | | return true; |
| | | 1050 | | } |
| | | 1051 | | } |
| | | 1052 | | |
| | 6 | 1053 | | _logger.LogDebug("{Source}: Matching bind address override found: {Address}", source, bindPreference); |
| | | 1054 | | |
| | 6 | 1055 | | return true; |
| | | 1056 | | } |
| | | 1057 | | |
| | | 1058 | | /// <summary> |
| | | 1059 | | /// Attempts to match the source against the user defined bind interfaces. |
| | | 1060 | | /// </summary> |
| | | 1061 | | /// <param name="source">IP source address to use.</param> |
| | | 1062 | | /// <param name="isInExternalSubnet">True if the source is in the external subnet.</param> |
| | | 1063 | | /// <param name="result">The result, if a match is found.</param> |
| | | 1064 | | /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> |
| | | 1065 | | private bool MatchesBindInterface(IPAddress source, bool isInExternalSubnet, out string result) |
| | | 1066 | | { |
| | 13 | 1067 | | result = string.Empty; |
| | | 1068 | | |
| | 13 | 1069 | | int count = _interfaces.Count; |
| | 13 | 1070 | | if (count == 1 && (_interfaces[0].Address.Equals(IPAddress.Any) || _interfaces[0].Address.Equals(IPAddress.IPv6A |
| | | 1071 | | { |
| | | 1072 | | // Ignore IPAny addresses. |
| | 0 | 1073 | | count = 0; |
| | | 1074 | | } |
| | | 1075 | | |
| | 13 | 1076 | | if (count == 0) |
| | | 1077 | | { |
| | 0 | 1078 | | return false; |
| | | 1079 | | } |
| | | 1080 | | |
| | 13 | 1081 | | IPAddress? bindAddress = null; |
| | 13 | 1082 | | if (isInExternalSubnet) |
| | | 1083 | | { |
| | 5 | 1084 | | var externalInterfaces = _interfaces.Where(x => !IsInLocalNetwork(x.Address)) |
| | 5 | 1085 | | .Where(x => !IsLinkLocalAddress(x.Address)) |
| | 5 | 1086 | | .OrderBy(x => x.Index) |
| | 5 | 1087 | | .ToList(); |
| | 5 | 1088 | | if (externalInterfaces.Count > 0) |
| | | 1089 | | { |
| | | 1090 | | // Check to see if any of the external bind interfaces are in the same subnet as the source. |
| | | 1091 | | // If none exists, this will select the first external interface if there is one. |
| | 4 | 1092 | | bindAddress = externalInterfaces |
| | 4 | 1093 | | .OrderByDescending(x => NetworkUtils.SubnetContainsAddress(x.Subnet, source)) |
| | 4 | 1094 | | .ThenByDescending(x => x.Subnet.PrefixLength) |
| | 4 | 1095 | | .ThenBy(x => x.Index) |
| | 4 | 1096 | | .Select(x => x.Address) |
| | 4 | 1097 | | .First(); |
| | | 1098 | | |
| | 4 | 1099 | | result = NetworkUtils.FormatIPString(bindAddress); |
| | 4 | 1100 | | _logger.LogDebug("{Source}: External request received, matching external bind address found: {Result}", |
| | 4 | 1101 | | return true; |
| | | 1102 | | } |
| | | 1103 | | |
| | 1 | 1104 | | _logger.LogDebug("{Source}: External request received, no matching external bind address found, trying inter |
| | | 1105 | | } |
| | | 1106 | | else |
| | | 1107 | | { |
| | | 1108 | | // Check to see if any of the internal bind interfaces are in the same subnet as the source. |
| | | 1109 | | // If none exists, this will select the first internal interface if there is one. |
| | 8 | 1110 | | bindAddress = _interfaces.Where(x => IsInLocalNetwork(x.Address)) |
| | 8 | 1111 | | .OrderByDescending(x => NetworkUtils.SubnetContainsAddress(x.Subnet, source)) |
| | 8 | 1112 | | .ThenByDescending(x => x.Subnet.PrefixLength) |
| | 8 | 1113 | | .ThenBy(x => x.Index) |
| | 8 | 1114 | | .Select(x => x.Address) |
| | 8 | 1115 | | .FirstOrDefault(); |
| | | 1116 | | |
| | 8 | 1117 | | if (bindAddress is not null) |
| | | 1118 | | { |
| | 7 | 1119 | | result = NetworkUtils.FormatIPString(bindAddress); |
| | 7 | 1120 | | _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", |
| | 7 | 1121 | | return true; |
| | | 1122 | | } |
| | | 1123 | | } |
| | | 1124 | | |
| | 2 | 1125 | | return false; |
| | | 1126 | | } |
| | | 1127 | | |
| | | 1128 | | /// <summary> |
| | | 1129 | | /// Attempts to match the source against external interfaces. |
| | | 1130 | | /// </summary> |
| | | 1131 | | /// <param name="source">IP source address to use.</param> |
| | | 1132 | | /// <param name="result">The result, if a match is found.</param> |
| | | 1133 | | /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> |
| | | 1134 | | private bool MatchesExternalInterface(IPAddress source, out string result) |
| | | 1135 | | { |
| | | 1136 | | // Get the first external interface address that isn't a loopback. |
| | 1 | 1137 | | var extResult = _interfaces |
| | 1 | 1138 | | .Where(p => !IsInLocalNetwork(p.Address)) |
| | 1 | 1139 | | .Where(p => p.Address.AddressFamily.Equals(source.AddressFamily)) |
| | 1 | 1140 | | .Where(p => !IsLinkLocalAddress(p.Address)) |
| | 1 | 1141 | | .OrderBy(x => x.Index).ToArray(); |
| | | 1142 | | |
| | | 1143 | | // No external interface found |
| | 1 | 1144 | | if (extResult.Length == 0) |
| | | 1145 | | { |
| | 1 | 1146 | | result = string.Empty; |
| | 1 | 1147 | | _logger.LogDebug("{Source}: External request received, but no external interface found. Need to route throug |
| | 1 | 1148 | | return false; |
| | | 1149 | | } |
| | | 1150 | | |
| | | 1151 | | // Does the request originate in one of the interface subnets? |
| | | 1152 | | // (For systems with multiple network cards and/or multiple subnets) |
| | 0 | 1153 | | foreach (var intf in extResult) |
| | | 1154 | | { |
| | 0 | 1155 | | if (NetworkUtils.SubnetContainsAddress(intf.Subnet, source)) |
| | | 1156 | | { |
| | 0 | 1157 | | result = NetworkUtils.FormatIPString(intf.Address); |
| | 0 | 1158 | | _logger.LogDebug("{Source}: Found external interface with matching subnet, using it as bind address: {Re |
| | 0 | 1159 | | return true; |
| | | 1160 | | } |
| | | 1161 | | } |
| | | 1162 | | |
| | | 1163 | | // Fallback to first external interface. |
| | 0 | 1164 | | result = NetworkUtils.FormatIPString(extResult[0].Address); |
| | 0 | 1165 | | _logger.LogDebug("{Source}: Using first external interface as bind address: {Result}", source, result); |
| | 0 | 1166 | | return true; |
| | | 1167 | | } |
| | | 1168 | | |
| | | 1169 | | private void PrintNetworkInformation(NetworkConfiguration config, bool debug = true) |
| | | 1170 | | { |
| | 79 | 1171 | | var logLevel = debug ? LogLevel.Debug : LogLevel.Information; |
| | 79 | 1172 | | if (_logger.IsEnabled(logLevel)) |
| | | 1173 | | { |
| | 21 | 1174 | | _logger.Log(logLevel, "Defined LAN subnets: {Subnets}", _lanSubnets.Select(s => s.Prefix + "/" + s.PrefixLen |
| | 21 | 1175 | | _logger.Log(logLevel, "Defined LAN exclusions: {Subnets}", _excludedSubnets.Select(s => s.Prefix + "/" + s.P |
| | 21 | 1176 | | _logger.Log(logLevel, "Used LAN subnets: {Subnets}", _lanSubnets.Where(s => !_excludedSubnets.Contains(s)).S |
| | 21 | 1177 | | _logger.Log(logLevel, "Filtered interface addresses: {Addresses}", _interfaces.OrderByDescending(x => x.Addr |
| | 21 | 1178 | | _logger.Log(logLevel, "Bind Addresses {Addresses}", GetAllBindInterfaces(false).OrderByDescending(x => x.Add |
| | 21 | 1179 | | _logger.Log(logLevel, "Remote IP filter is {Type}", config.IsRemoteIPFilterBlacklist ? "Blocklist" : "Allowl |
| | 21 | 1180 | | _logger.Log(logLevel, "Filtered subnets: {Subnets}", _remoteAddressFilter.Select(s => s.Prefix + "/" + s.Pre |
| | | 1181 | | } |
| | 79 | 1182 | | } |
| | | 1183 | | } |