NetworkManager.cs 45 KB

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