NetworkManager.cs 47 KB

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