NetworkManager.cs 43 KB

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