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