NetworkManager.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  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. _ = TryParseSubnets(subnets, out _lanSubnets, false);
  284. _ = 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. _ = 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. /// <summary>
  526. /// Try parsing an array of strings into subnets, respecting exclusions.
  527. /// </summary>
  528. /// <param name="values">Input string to be parsed.</param>
  529. /// <param name="result">Collection of <see cref="IPNetwork"/>.</param>
  530. /// <param name="negated">Boolean signaling if negated or not negated values should be parsed.</param>
  531. /// <returns><c>True</c> if parsing was successful.</returns>
  532. public bool TryParseSubnets(string[] values, out Collection<IPNetwork> result, bool negated = false)
  533. {
  534. result = new Collection<IPNetwork>();
  535. if (values == null || values.Length == 0)
  536. {
  537. return false;
  538. }
  539. for (int a = 0; a < values.Length; a++)
  540. {
  541. string[] v = values[a].Trim().Split("/");
  542. try
  543. {
  544. var address = IPAddress.None;
  545. if (negated && v[0].StartsWith('!'))
  546. {
  547. _ = IPAddress.TryParse(v[0][1..], out address);
  548. }
  549. else if (!negated)
  550. {
  551. _ = IPAddress.TryParse(v[0][0..], out address);
  552. }
  553. if (address != IPAddress.None && address != null)
  554. {
  555. if (int.TryParse(v[1], out var netmask))
  556. {
  557. result.Add(new IPNetwork(address, netmask));
  558. }
  559. else if (address.AddressFamily == AddressFamily.InterNetwork)
  560. {
  561. result.Add(new IPNetwork(address, 32));
  562. }
  563. else if (address.AddressFamily == AddressFamily.InterNetworkV6)
  564. {
  565. result.Add(new IPNetwork(address, 128));
  566. }
  567. }
  568. }
  569. catch (ArgumentException e)
  570. {
  571. _logger.LogWarning(e, "Ignoring LAN value {Value}.", v);
  572. }
  573. }
  574. if (result.Count > 0)
  575. {
  576. return true;
  577. }
  578. return false;
  579. }
  580. /// <inheritdoc/>
  581. public bool HasRemoteAccess(IPAddress remoteIp)
  582. {
  583. var config = _configurationManager.GetNetworkConfiguration();
  584. if (config.EnableRemoteAccess)
  585. {
  586. // Comma separated list of IP addresses or IP/netmask entries for networks that will be allowed to connect remotely.
  587. // If left blank, all remote addresses will be allowed.
  588. if (_remoteAddressFilter.Any() && !_lanSubnets.Any(x => x.Contains(remoteIp)))
  589. {
  590. // remoteAddressFilter is a whitelist or blacklist.
  591. var matches = _remoteAddressFilter.Count(remoteNetwork => remoteNetwork.Contains(remoteIp));
  592. if ((!config.IsRemoteIPFilterBlacklist && matches > 0)
  593. || (config.IsRemoteIPFilterBlacklist && matches == 0))
  594. {
  595. return true;
  596. }
  597. return false;
  598. }
  599. }
  600. else if (!_lanSubnets.Where(x => x.Contains(remoteIp)).Any())
  601. {
  602. // Remote not enabled. So everyone should be LAN.
  603. return false;
  604. }
  605. return true;
  606. }
  607. /// <inheritdoc/>
  608. public IReadOnlyCollection<PhysicalAddress> GetMacAddresses()
  609. {
  610. // Populated in construction - so always has values.
  611. return _macAddresses;
  612. }
  613. /// <inheritdoc/>
  614. public List<IPData> GetLoopbacks()
  615. {
  616. var loopbackNetworks = new List<IPData>();
  617. if (IsIpv4Enabled)
  618. {
  619. loopbackNetworks.Add(new IPData(IPAddress.Loopback, new IPNetwork(IPAddress.Loopback, 8), "lo"));
  620. }
  621. if (IsIpv6Enabled)
  622. {
  623. loopbackNetworks.Add(new IPData(IPAddress.IPv6Loopback, new IPNetwork(IPAddress.IPv6Loopback, 128), "lo"));
  624. }
  625. return loopbackNetworks;
  626. }
  627. /// <inheritdoc/>
  628. public List<IPData> GetAllBindInterfaces(bool individualInterfaces = false)
  629. {
  630. if (_bindAddresses.Count == 0)
  631. {
  632. if (_bindExclusions.Count > 0)
  633. {
  634. foreach (var exclusion in _bindExclusions)
  635. {
  636. // Return all the interfaces except the ones specifically excluded.
  637. _interfaces.RemoveAll(intf => intf.Address == exclusion);
  638. }
  639. return _interfaces;
  640. }
  641. // No bind address and no exclusions, so listen on all interfaces.
  642. var result = new List<IPData>();
  643. if (individualInterfaces)
  644. {
  645. foreach (var iface in _interfaces)
  646. {
  647. result.Add(iface);
  648. }
  649. return result;
  650. }
  651. if (IsIpv4Enabled && IsIpv6Enabled)
  652. {
  653. // Kestrel source code shows it uses Sockets.DualMode - so this also covers IPAddress.Any by default
  654. result.Add(new IPData(IPAddress.IPv6Any, new IPNetwork(IPAddress.IPv6Any, 0)));
  655. }
  656. else if (IsIpv4Enabled)
  657. {
  658. result.Add(new IPData(IPAddress.Any, new IPNetwork(IPAddress.Any, 0)));
  659. }
  660. else if (IsIpv6Enabled)
  661. {
  662. // Cannot use IPv6Any as Kestrel will bind to IPv4 addresses too.
  663. foreach (var iface in _interfaces)
  664. {
  665. if (iface.AddressFamily == AddressFamily.InterNetworkV6)
  666. {
  667. result.Add(iface);
  668. }
  669. }
  670. }
  671. return result;
  672. }
  673. // Remove any excluded bind interfaces.
  674. foreach (var exclusion in _bindExclusions)
  675. {
  676. // Return all the interfaces except the ones specifically excluded.
  677. _bindAddresses.Remove(exclusion);
  678. }
  679. return _bindAddresses.Select(s => new IPData(s, null)).ToList();
  680. }
  681. /// <inheritdoc/>
  682. public string GetBindInterface(string source, out int? port)
  683. {
  684. _ = NetworkExtensions.TryParseHost(source, out var address, IsIpv4Enabled, IsIpv6Enabled);
  685. var result = GetBindInterface(address.FirstOrDefault(), out port);
  686. return result;
  687. }
  688. /// <inheritdoc/>
  689. public string GetBindInterface(HttpRequest source, out int? port)
  690. {
  691. string result;
  692. _ = NetworkExtensions.TryParseHost(source.Host.Host, out var addresses, IsIpv4Enabled, IsIpv6Enabled);
  693. result = GetBindInterface(addresses.FirstOrDefault(), out port);
  694. port ??= source.Host.Port;
  695. return result;
  696. }
  697. /// <inheritdoc/>
  698. public string GetBindInterface(IPAddress? source, out int? port)
  699. {
  700. port = null;
  701. string result;
  702. if (source != null)
  703. {
  704. if (IsIpv4Enabled && source.AddressFamily == AddressFamily.InterNetworkV6)
  705. {
  706. _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
  707. }
  708. if (IsIpv6Enabled && source.AddressFamily == AddressFamily.InterNetwork)
  709. {
  710. _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
  711. }
  712. bool isExternal = !_lanSubnets.Any(network => network.Contains(source));
  713. _logger.LogDebug("GetBindInterface with source. External: {IsExternal}:", isExternal);
  714. if (MatchesPublishedServerUrl(source, isExternal, out string res, out port))
  715. {
  716. _logger.LogInformation("{Source}: Using BindAddress {Address}:{Port}", source, res, port);
  717. return res;
  718. }
  719. // No preference given, so move on to bind addresses.
  720. if (MatchesBindInterface(source, isExternal, out result))
  721. {
  722. return result;
  723. }
  724. if (isExternal && MatchesExternalInterface(source, out result))
  725. {
  726. return result;
  727. }
  728. }
  729. // Get the first LAN interface address that's not excluded and not a loopback address.
  730. var availableInterfaces = _interfaces.Where(x => !IPAddress.IsLoopback(x.Address))
  731. .OrderByDescending(x => _bindAddresses.Contains(x.Address))
  732. .ThenByDescending(x => IsInLocalNetwork(x.Address))
  733. .ThenBy(x => x.Index);
  734. if (availableInterfaces.Any())
  735. {
  736. if (source != null)
  737. {
  738. foreach (var intf in availableInterfaces)
  739. {
  740. if (intf.Address.Equals(source))
  741. {
  742. result = NetworkExtensions.FormatIpString(intf.Address);
  743. _logger.LogDebug("{Source}: GetBindInterface: Has found matching interface. {Result}", source, result);
  744. return result;
  745. }
  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 = NetworkExtensions.FormatIpString(intf.Address);
  754. _logger.LogDebug("{Source}: GetBindInterface: Has source, matched best internal interface on range. {Result}", source, result);
  755. return result;
  756. }
  757. }
  758. }
  759. result = NetworkExtensions.FormatIpString(availableInterfaces.First().Address);
  760. _logger.LogDebug("{Source}: GetBindInterface: Matched first internal interface. {Result}", source, result);
  761. return result;
  762. }
  763. // There isn't any others, so we'll use the loopback.
  764. result = IsIpv4Enabled && !IsIpv6Enabled ? "127.0.0.1" : "::1";
  765. _logger.LogWarning("{Source}: GetBindInterface: Loopback {Result} returned.", source, result);
  766. return result;
  767. }
  768. /// <inheritdoc/>
  769. public List<IPData> GetInternalBindAddresses()
  770. {
  771. if (_bindAddresses.Count == 0)
  772. {
  773. if (_bindExclusions.Count > 0)
  774. {
  775. // Return all the internal interfaces except the ones excluded.
  776. return _interfaces.Where(p => !_bindExclusions.Contains(p.Address)).ToList();
  777. }
  778. // No bind address, so return all internal interfaces.
  779. return _interfaces;
  780. }
  781. // Select all local bind addresses
  782. return _interfaces.Where(x => _bindAddresses.Contains(x.Address))
  783. .Where(x => IsInLocalNetwork(x.Address))
  784. .OrderBy(x => x.Index).ToList();
  785. }
  786. /// <inheritdoc/>
  787. public bool IsInLocalNetwork(string address)
  788. {
  789. if (IPAddress.TryParse(address, out var ep))
  790. {
  791. return IPAddress.IsLoopback(ep) || (_lanSubnets.Any(x => x.Contains(ep)) && !_excludedSubnets.Any(x => x.Contains(ep)));
  792. }
  793. if (NetworkExtensions.TryParseHost(address, out var addresses, IsIpv4Enabled, IsIpv6Enabled))
  794. {
  795. bool match = false;
  796. foreach (var ept in addresses)
  797. {
  798. match |= IPAddress.IsLoopback(ept) || (_lanSubnets.Any(x => x.Contains(ept)) && !_excludedSubnets.Any(x => x.Contains(ept)));
  799. }
  800. return match;
  801. }
  802. return false;
  803. }
  804. /// <inheritdoc/>
  805. public bool IsInLocalNetwork(IPAddress address)
  806. {
  807. if (address == null)
  808. {
  809. throw new ArgumentNullException(nameof(address));
  810. }
  811. // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
  812. if (TrustAllIpv6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
  813. {
  814. return true;
  815. }
  816. // As private addresses can be redefined by Configuration.LocalNetworkAddresses
  817. var match = CheckIfLanAndNotExcluded(address);
  818. return address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback) || match;
  819. }
  820. private IPData? FindInterfaceForIp(IPAddress address, bool localNetwork = false)
  821. {
  822. if (address == null)
  823. {
  824. throw new ArgumentNullException(nameof(address));
  825. }
  826. var interfaces = _interfaces;
  827. if (localNetwork)
  828. {
  829. interfaces = interfaces.Where(x => IsInLocalNetwork(x.Address)).ToList();
  830. }
  831. foreach (var intf in _interfaces)
  832. {
  833. if (intf.Subnet.Contains(address))
  834. {
  835. return intf;
  836. }
  837. }
  838. return null;
  839. }
  840. private bool CheckIfLanAndNotExcluded(IPAddress address)
  841. {
  842. bool match = false;
  843. foreach (var lanSubnet in _lanSubnets)
  844. {
  845. match |= lanSubnet.Contains(address);
  846. }
  847. foreach (var excludedSubnet in _excludedSubnets)
  848. {
  849. match &= !excludedSubnet.Contains(address);
  850. }
  851. NetworkExtensions.IsIPv6LinkLocal(address);
  852. return match;
  853. }
  854. /// <summary>
  855. /// Attempts to match the source against the published server URL overrides.
  856. /// </summary>
  857. /// <param name="source">IP source address to use.</param>
  858. /// <param name="isInExternalSubnet">True if the source is in an external subnet.</param>
  859. /// <param name="bindPreference">The published server URL that matches the source address.</param>
  860. /// <param name="port">The resultant port, if one exists.</param>
  861. /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
  862. private bool MatchesPublishedServerUrl(IPAddress source, bool isInExternalSubnet, out string bindPreference, out int? port)
  863. {
  864. bindPreference = string.Empty;
  865. port = null;
  866. var validPublishedServerUrls = _publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.Any)).ToList();
  867. validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Address.Equals(IPAddress.IPv6Any)));
  868. validPublishedServerUrls.AddRange(_publishedServerUrls.Where(x => x.Key.Subnet.Contains(source)));
  869. validPublishedServerUrls = validPublishedServerUrls.GroupBy(x => x.Key).Select(y => y.First()).ToList();
  870. // Check for user override.
  871. foreach (var data in validPublishedServerUrls)
  872. {
  873. // Get address interface
  874. var intf = _interfaces.FirstOrDefault(s => s.Subnet.Contains(data.Key.Address));
  875. // Remaining. Match anything.
  876. if (data.Key.Address.Equals(IPAddress.Broadcast))
  877. {
  878. bindPreference = data.Value;
  879. break;
  880. }
  881. else if ((data.Key.Address.Equals(IPAddress.Any) || data.Key.Address.Equals(IPAddress.IPv6Any)) && isInExternalSubnet)
  882. {
  883. // External.
  884. bindPreference = data.Value;
  885. break;
  886. }
  887. else if (intf?.Address != null)
  888. {
  889. // Match ip address.
  890. bindPreference = data.Value;
  891. break;
  892. }
  893. }
  894. if (string.IsNullOrEmpty(bindPreference))
  895. {
  896. return false;
  897. }
  898. // Has it got a port defined?
  899. var parts = bindPreference.Split(':');
  900. if (parts.Length > 1)
  901. {
  902. if (int.TryParse(parts[1], out int p))
  903. {
  904. bindPreference = parts[0];
  905. port = p;
  906. }
  907. }
  908. return true;
  909. }
  910. /// <summary>
  911. /// Attempts to match the source against a user defined bind interface.
  912. /// </summary>
  913. /// <param name="source">IP source address to use.</param>
  914. /// <param name="isInExternalSubnet">True if the source is in the external subnet.</param>
  915. /// <param name="result">The result, if a match is found.</param>
  916. /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
  917. private bool MatchesBindInterface(IPAddress source, bool isInExternalSubnet, out string result)
  918. {
  919. result = string.Empty;
  920. int count = _bindAddresses.Count;
  921. if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any)))
  922. {
  923. // Ignore IPAny addresses.
  924. count = 0;
  925. }
  926. if (count != 0)
  927. {
  928. // Check to see if any of the bind interfaces are in the same subnet as the source.
  929. IPAddress? defaultGateway = null;
  930. IPAddress? bindAddress = null;
  931. if (isInExternalSubnet)
  932. {
  933. // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first.
  934. foreach (var addr in _bindAddresses)
  935. {
  936. if (defaultGateway == null && !IsInLocalNetwork(addr))
  937. {
  938. defaultGateway = addr;
  939. }
  940. var intf = _interfaces.Where(x => x.Subnet.Contains(addr)).FirstOrDefault();
  941. if (bindAddress == null && intf != null && intf.Subnet.Contains(source))
  942. {
  943. bindAddress = intf.Address;
  944. }
  945. if (defaultGateway != null && bindAddress != null)
  946. {
  947. break;
  948. }
  949. }
  950. }
  951. else
  952. {
  953. // Look for the best internal address.
  954. foreach (var bA in _bindAddresses.Where(x => IsInLocalNetwork(x)))
  955. {
  956. var intf = FindInterfaceForIp(source, true);
  957. if (intf != null)
  958. {
  959. bindAddress = intf.Address;
  960. break;
  961. }
  962. }
  963. }
  964. if (bindAddress != null)
  965. {
  966. result = NetworkExtensions.FormatIpString(bindAddress);
  967. _logger.LogDebug("{Source}: GetBindInterface: Has source, found a matching bind interface subnet. {Result}", source, result);
  968. return true;
  969. }
  970. if (isInExternalSubnet && defaultGateway != null)
  971. {
  972. result = NetworkExtensions.FormatIpString(defaultGateway);
  973. _logger.LogDebug("{Source}: GetBindInterface: Using first user defined external interface. {Result}", source, result);
  974. return true;
  975. }
  976. result = NetworkExtensions.FormatIpString(_bindAddresses[0]);
  977. _logger.LogDebug("{Source}: GetBindInterface: Selected first user defined interface. {Result}", source, result);
  978. if (isInExternalSubnet)
  979. {
  980. _logger.LogWarning("{Source}: External request received, only an internal interface bind found.", source);
  981. }
  982. return true;
  983. }
  984. return false;
  985. }
  986. /// <summary>
  987. /// Attempts to match the source against an external interface.
  988. /// </summary>
  989. /// <param name="source">IP source address to use.</param>
  990. /// <param name="result">The result, if a match is found.</param>
  991. /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns>
  992. private bool MatchesExternalInterface(IPAddress source, out string result)
  993. {
  994. result = string.Empty;
  995. // Get the first WAN interface address that isn't a loopback.
  996. var extResult = _interfaces.Where(p => !IsInLocalNetwork(p.Address));
  997. IPAddress? hasResult = null;
  998. // Does the request originate in one of the interface subnets?
  999. // (For systems with multiple internal network cards, and multiple subnets)
  1000. foreach (var intf in extResult)
  1001. {
  1002. hasResult ??= intf.Address;
  1003. if (!IsInLocalNetwork(intf.Address) && intf.Subnet.Contains(source))
  1004. {
  1005. result = NetworkExtensions.FormatIpString(intf.Address);
  1006. _logger.LogDebug("{Source}: GetBindInterface: Selected best external on interface on range. {Result}", source, result);
  1007. return true;
  1008. }
  1009. }
  1010. if (hasResult != null)
  1011. {
  1012. result = NetworkExtensions.FormatIpString(hasResult);
  1013. _logger.LogDebug("{Source}: GetBindInterface: Selected first external interface. {Result}", source, result);
  1014. return true;
  1015. }
  1016. _logger.LogDebug("{Source}: External request received, but no WAN interface found. Need to route through internal network.", source);
  1017. return false;
  1018. }
  1019. }
  1020. }