NetworkManager.cs 47 KB

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