NetworkManager.cs 44 KB

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