NetworkManager.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240
  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.Tasks;
  9. using Jellyfin.Networking.Configuration;
  10. using MediaBrowser.Common.Configuration;
  11. using MediaBrowser.Common.Net;
  12. using Microsoft.AspNetCore.Http;
  13. using Microsoft.Extensions.Logging;
  14. using NetworkCollection;
  15. using NetworkCollection.Udp;
  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. /// Contains the description of the interface along with its index.
  25. /// </summary>
  26. private readonly Dictionary<string, int> _interfaceNames;
  27. /// <summary>
  28. /// Threading lock for network interfaces.
  29. /// </summary>
  30. private readonly object _intLock = new object();
  31. /// <summary>
  32. /// List of all interface addresses and masks.
  33. /// </summary>
  34. private readonly NetCollection _interfaceAddresses;
  35. /// <summary>
  36. /// List of all interface MAC addresses.
  37. /// </summary>
  38. private readonly List<PhysicalAddress> _macAddresses;
  39. private readonly ILogger<NetworkManager> _logger;
  40. private readonly IConfigurationManager _configurationManager;
  41. private readonly object _eventFireLock;
  42. /// <summary>
  43. /// Holds the bind address overrides.
  44. /// </summary>
  45. private readonly Dictionary<IPNetAddress, string> _publishedServerUrls;
  46. /// <summary>
  47. /// Used to stop "event-racing conditions".
  48. /// </summary>
  49. private bool _eventfire;
  50. /// <summary>
  51. /// Unfiltered user defined LAN subnets. (Configuration.LocalNetworkSubnets).
  52. /// or internal interface network subnets if undefined by user.
  53. /// </summary>
  54. private NetCollection _lanSubnets;
  55. /// <summary>
  56. /// User defined list of subnets to excluded from the LAN.
  57. /// </summary>
  58. private NetCollection _excludedSubnets;
  59. /// <summary>
  60. /// List of interface addresses to bind the WS.
  61. /// </summary>
  62. private NetCollection _bindAddresses;
  63. /// <summary>
  64. /// List of interface addresses to exclude from bind.
  65. /// </summary>
  66. private NetCollection _bindExclusions;
  67. /// <summary>
  68. /// Caches list of all internal filtered interface addresses and masks.
  69. /// </summary>
  70. private NetCollection _internalInterfaces;
  71. /// <summary>
  72. /// Flag set when no custom LAN has been defined in the config.
  73. /// </summary>
  74. private bool _usingPrivateAddresses;
  75. /// <summary>
  76. /// True if this object is disposed.
  77. /// </summary>
  78. private bool _disposed;
  79. /// <summary>
  80. /// Initializes a new instance of the <see cref="NetworkManager"/> class.
  81. /// </summary>
  82. /// <param name="configurationManager">IServerConfigurationManager instance.</param>
  83. /// <param name="logger">Logger to use for messages.</param>
  84. #pragma warning disable CS8618 // Non-nullable field is uninitialized. : Values are set in UpdateSettings function. Compiler doesn't yet recognise this.
  85. public NetworkManager(IConfigurationManager configurationManager, ILogger<NetworkManager> logger)
  86. {
  87. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  88. _configurationManager = configurationManager ?? throw new ArgumentNullException(nameof(configurationManager));
  89. _interfaceAddresses = new NetCollection(unique: false);
  90. _macAddresses = new List<PhysicalAddress>();
  91. _interfaceNames = new Dictionary<string, int>();
  92. _publishedServerUrls = new Dictionary<IPNetAddress, string>();
  93. _eventFireLock = new object();
  94. NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged;
  95. NetworkChange.NetworkAvailabilityChanged += OnNetworkAvailabilityChanged;
  96. _configurationManager.ConfigurationUpdated += ConfigurationUpdated;
  97. }
  98. #pragma warning restore CS8618 // Non-nullable field is uninitialized.
  99. /// <summary>
  100. /// Event triggered on network changes.
  101. /// </summary>
  102. public event EventHandler? NetworkChanged;
  103. /// <summary>
  104. /// Gets or sets a value indicating whether testing is taking place.
  105. /// </summary>
  106. public static string MockNetworkSettings { get; set; } = string.Empty;
  107. /// <summary>
  108. /// Gets or sets a value indicating whether IP6 is enabled.
  109. /// </summary>
  110. public bool IsIP6Enabled { get; set; }
  111. /// <summary>
  112. /// Gets or sets a value indicating whether IP4 is enabled.
  113. /// </summary>
  114. public bool IsIP4Enabled { get; set; }
  115. /// <inheritdoc/>
  116. public NetCollection RemoteAddressFilter { get; private set; }
  117. /// <summary>
  118. /// Gets a value indicating whether is all IPv6 interfaces are trusted as internal.
  119. /// </summary>
  120. public bool TrustAllIP6Interfaces { get; internal set; }
  121. /// <summary>
  122. /// Gets the Published server override list.
  123. /// </summary>
  124. public Dictionary<IPNetAddress, string> PublishedServerUrls => _publishedServerUrls;
  125. /// <inheritdoc/>
  126. public void Dispose()
  127. {
  128. Dispose(true);
  129. GC.SuppressFinalize(this);
  130. }
  131. /// <inheritdoc/>
  132. public List<PhysicalAddress> GetMacAddresses()
  133. {
  134. // Populated in construction - so always has values.
  135. return _macAddresses.ToList();
  136. }
  137. /// <inheritdoc/>
  138. public bool IsGatewayInterface(object? addressObj)
  139. {
  140. var address = addressObj switch
  141. {
  142. IPAddress addressIp => addressIp,
  143. IPObject addressIpObj => addressIpObj.Address,
  144. _ => IPAddress.None
  145. };
  146. return _internalInterfaces.Any(i => i.Address.Equals(address) && i.Tag < 0);
  147. }
  148. /// <inheritdoc/>
  149. public NetCollection GetLoopbacks()
  150. {
  151. NetCollection nc = new NetCollection();
  152. if (IsIP4Enabled)
  153. {
  154. nc.Add(IPAddress.Loopback);
  155. }
  156. if (IsIP6Enabled)
  157. {
  158. nc.Add(IPAddress.IPv6Loopback);
  159. }
  160. return nc;
  161. }
  162. /// <inheritdoc/>
  163. public bool IsExcluded(IPAddress ip)
  164. {
  165. return _excludedSubnets.Contains(ip);
  166. }
  167. /// <inheritdoc/>
  168. public bool IsExcluded(EndPoint ip)
  169. {
  170. return ip != null && IsExcluded(((IPEndPoint)ip).Address);
  171. }
  172. /// <inheritdoc/>
  173. public NetCollection CreateIPCollection(string[] values, bool bracketed = false)
  174. {
  175. NetCollection col = new NetCollection();
  176. if (values == null)
  177. {
  178. return col;
  179. }
  180. for (int a = 0; a < values.Length; a++)
  181. {
  182. string v = values[a].Trim();
  183. try
  184. {
  185. if (v.StartsWith('[') && v.EndsWith(']'))
  186. {
  187. if (bracketed)
  188. {
  189. AddToCollection(col, v.Substring(1, v.Length - 2));
  190. }
  191. }
  192. else if (v.StartsWith('!'))
  193. {
  194. if (bracketed)
  195. {
  196. AddToCollection(col, v.Substring(1));
  197. }
  198. }
  199. else if (!bracketed)
  200. {
  201. AddToCollection(col, v);
  202. }
  203. }
  204. catch (ArgumentException e)
  205. {
  206. _logger.LogInformation("Ignoring LAN value {value}. Reason : {reason}", v, e.Message);
  207. }
  208. }
  209. return col;
  210. }
  211. /// <inheritdoc/>
  212. public NetCollection GetAllBindInterfaces(bool individualInterfaces = false)
  213. {
  214. int count = _bindAddresses.Count;
  215. if (count == 0)
  216. {
  217. if (_bindExclusions.Count > 0)
  218. {
  219. // Return all the interfaces except the ones specifically excluded.
  220. return _interfaceAddresses.Exclude(_bindExclusions);
  221. }
  222. if (individualInterfaces)
  223. {
  224. return new NetCollection(_interfaceAddresses);
  225. }
  226. // No bind address and no exclusions, so listen on all interfaces.
  227. NetCollection result = new NetCollection();
  228. if (IsIP4Enabled)
  229. {
  230. result.Add(IPAddress.Any);
  231. }
  232. if (IsIP6Enabled)
  233. {
  234. result.Add(IPAddress.IPv6Any);
  235. }
  236. return result;
  237. }
  238. // Remove any excluded bind interfaces.
  239. return _bindAddresses.Exclude(_bindExclusions);
  240. }
  241. /// <inheritdoc/>
  242. public string GetBindInterface(string source, out int? port)
  243. {
  244. if (!string.IsNullOrEmpty(source) && IPHost.TryParse(source, out IPHost host))
  245. {
  246. return GetBindInterface(host, out port);
  247. }
  248. return GetBindInterface(IPHost.None, out port);
  249. }
  250. /// <inheritdoc/>
  251. public string GetBindInterface(IPAddress source, out int? port)
  252. {
  253. return GetBindInterface(new IPNetAddress(source), out port);
  254. }
  255. /// <inheritdoc/>
  256. public string GetBindInterface(HttpRequest source, out int? port)
  257. {
  258. string result;
  259. if (source != null && IPHost.TryParse(source.Host.Host, out IPHost host))
  260. {
  261. result = GetBindInterface(host, out port);
  262. port ??= source.Host.Port;
  263. }
  264. else
  265. {
  266. result = GetBindInterface(IPNetAddress.None, out port);
  267. port ??= source?.Host.Port;
  268. }
  269. return result;
  270. }
  271. /// <inheritdoc/>
  272. public string GetBindInterface(IPObject source, out int? port)
  273. {
  274. port = null;
  275. // Do we have a source?
  276. bool haveSource = !source.Address.Equals(IPAddress.None);
  277. bool isExternal = false;
  278. if (haveSource)
  279. {
  280. if (!IsIP6Enabled && source.AddressFamily == AddressFamily.InterNetworkV6)
  281. {
  282. _logger.LogWarning("IPv6 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
  283. }
  284. if (!IsIP4Enabled && source.AddressFamily == AddressFamily.InterNetwork)
  285. {
  286. _logger.LogWarning("IPv4 is disabled in Jellyfin, but enabled in the OS. This may affect how the interface is selected.");
  287. }
  288. isExternal = !IsInLocalNetwork(source);
  289. if (MatchesPublishedServerUrl(source, isExternal, out string res, out port))
  290. {
  291. _logger.LogInformation("{0}: Using BindAddress {1}:{2}", source, res, port);
  292. return res;
  293. }
  294. }
  295. _logger.LogDebug("GetBindInterface: Source: {0}, External: {1}:", haveSource, isExternal);
  296. // No preference given, so move on to bind addresses.
  297. if (MatchesBindInterface(source, isExternal, out string result))
  298. {
  299. return result;
  300. }
  301. if (isExternal && MatchesExternalInterface(source, out result))
  302. {
  303. return result;
  304. }
  305. // Get the first LAN interface address that isn't a loopback.
  306. var interfaces = new NetCollection(_interfaceAddresses
  307. .Exclude(_bindExclusions)
  308. .Where(p => IsInLocalNetwork(p))
  309. .OrderBy(p => p.Tag));
  310. if (interfaces.Count > 0)
  311. {
  312. if (haveSource)
  313. {
  314. // Does the request originate in one of the interface subnets?
  315. // (For systems with multiple internal network cards, and multiple subnets)
  316. foreach (var intf in interfaces)
  317. {
  318. if (intf.Contains(source))
  319. {
  320. result = FormatIP6String(intf.Address);
  321. _logger.LogDebug("{0}: GetBindInterface: Has source, matched best internal interface on range. {1}", source, result);
  322. return result;
  323. }
  324. }
  325. }
  326. result = FormatIP6String(interfaces.First().Address);
  327. _logger.LogDebug("{0}: GetBindInterface: Matched first internal interface. {1}", source, result);
  328. return result;
  329. }
  330. // There isn't any others, so we'll use the loopback.
  331. result = IsIP6Enabled ? "::" : "127.0.0.1";
  332. _logger.LogWarning("{0}: GetBindInterface: Loopback return.", source, result);
  333. return result;
  334. }
  335. /// <inheritdoc/>
  336. public NetCollection GetInternalBindAddresses()
  337. {
  338. int count = _bindAddresses.Count;
  339. if (count == 0)
  340. {
  341. if (_bindExclusions.Count > 0)
  342. {
  343. // Return all the internal interfaces except the ones excluded.
  344. return new NetCollection(_internalInterfaces.Where(p => !_bindExclusions.Contains(p)));
  345. }
  346. // No bind address, so return all internal interfaces.
  347. return new NetCollection(_internalInterfaces.Where(p => !p.IsLoopback()));
  348. }
  349. return new NetCollection(_bindAddresses);
  350. }
  351. /// <inheritdoc/>
  352. public bool IsInLocalNetwork(IPObject address)
  353. {
  354. if (address == null)
  355. {
  356. throw new ArgumentNullException(nameof(address));
  357. }
  358. if (address.Equals(IPAddress.None))
  359. {
  360. return false;
  361. }
  362. // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
  363. if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
  364. {
  365. return true;
  366. }
  367. // As private addresses can be redefined by Configuration.LocalNetworkAddresses
  368. return _lanSubnets.Contains(address) && !_excludedSubnets.Contains(address);
  369. }
  370. /// <inheritdoc/>
  371. public bool IsInLocalNetwork(string address)
  372. {
  373. if (IPHost.TryParse(address, out IPHost ep))
  374. {
  375. return _lanSubnets.Contains(ep) && !_excludedSubnets.Contains(ep);
  376. }
  377. return false;
  378. }
  379. /// <inheritdoc/>
  380. public bool IsInLocalNetwork(IPAddress address)
  381. {
  382. if (address == null)
  383. {
  384. throw new ArgumentNullException(nameof(address));
  385. }
  386. // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
  387. if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
  388. {
  389. return true;
  390. }
  391. // As private addresses can be redefined by Configuration.LocalNetworkAddresses
  392. return _lanSubnets.Contains(address) && !_excludedSubnets.Contains(address);
  393. }
  394. /// <inheritdoc/>
  395. public bool IsPrivateAddressRange(IPObject address)
  396. {
  397. if (address == null)
  398. {
  399. throw new ArgumentNullException(nameof(address));
  400. }
  401. // See conversation at https://github.com/jellyfin/jellyfin/pull/3515.
  402. if (TrustAllIP6Interfaces && address.AddressFamily == AddressFamily.InterNetworkV6)
  403. {
  404. return true;
  405. }
  406. else
  407. {
  408. return address.IsPrivateAddressRange();
  409. }
  410. }
  411. /// <inheritdoc/>
  412. public bool IsExcludedInterface(IPAddress address)
  413. {
  414. return _bindExclusions.Contains(address);
  415. }
  416. /// <inheritdoc/>
  417. public NetCollection GetFilteredLANSubnets(NetCollection? filter = null)
  418. {
  419. if (filter == null)
  420. {
  421. return NetCollection.AsNetworks(_lanSubnets.Exclude(_excludedSubnets));
  422. }
  423. return _lanSubnets.Exclude(filter);
  424. }
  425. /// <inheritdoc/>
  426. public bool IsValidInterfaceAddress(IPAddress address)
  427. {
  428. return _interfaceAddresses.Contains(address);
  429. }
  430. /// <inheritdoc/>
  431. public bool TryParseInterface(string token, out NetCollection? result)
  432. {
  433. result = null;
  434. if (string.IsNullOrEmpty(token))
  435. {
  436. return false;
  437. }
  438. if (_interfaceNames != null && _interfaceNames.TryGetValue(token.ToLower(CultureInfo.InvariantCulture), out int index))
  439. {
  440. result = new NetCollection();
  441. _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token);
  442. // Replace interface tags with the interface IP's.
  443. foreach (IPNetAddress iface in _interfaceAddresses)
  444. {
  445. if (Math.Abs(iface.Tag) == index &&
  446. ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) ||
  447. (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
  448. {
  449. result.Add(iface);
  450. }
  451. }
  452. return true;
  453. }
  454. return false;
  455. }
  456. /// <summary>
  457. /// Reloads all settings and re-initialises the instance.
  458. /// </summary>
  459. /// <param name="configuration">The configuration to use.</param>
  460. public void UpdateSettings(object configuration)
  461. {
  462. NetworkConfiguration config = (NetworkConfiguration)configuration ?? throw new ArgumentNullException(nameof(configuration));
  463. IsIP4Enabled = Socket.OSSupportsIPv4 && config.EnableIPV4;
  464. IsIP6Enabled = Socket.OSSupportsIPv6 && config.EnableIPV6;
  465. if (!IsIP6Enabled && !IsIP4Enabled)
  466. {
  467. _logger.LogError("IPv4 and IPv6 cannot both be disabled.");
  468. IsIP4Enabled = true;
  469. }
  470. TrustAllIP6Interfaces = config.TrustAllIP6Interfaces;
  471. UdpHelper.EnableMultiSocketBinding = config.EnableMultiSocketBinding;
  472. if (string.IsNullOrEmpty(MockNetworkSettings))
  473. {
  474. InitialiseInterfaces();
  475. }
  476. else // Used in testing only.
  477. {
  478. // Format is <IPAddress>,<Index>,<Name>: <next interface>. Set index to -ve to simulate a gateway.
  479. var interfaceList = MockNetworkSettings.Split(':');
  480. foreach (var details in interfaceList)
  481. {
  482. var parts = details.Split(',');
  483. var address = IPNetAddress.Parse(parts[0]);
  484. var index = int.Parse(parts[1], CultureInfo.InvariantCulture);
  485. address.Tag = index;
  486. _interfaceAddresses.Add(address);
  487. _interfaceNames.Add(parts[2], Math.Abs(index));
  488. }
  489. }
  490. InitialiseLAN(config);
  491. InitialiseBind(config);
  492. InitialiseRemote(config);
  493. InitialiseOverrides(config);
  494. }
  495. /// <summary>
  496. /// Protected implementation of Dispose pattern.
  497. /// </summary>
  498. /// <param name="disposing">True to dispose the managed state.</param>
  499. protected virtual void Dispose(bool disposing)
  500. {
  501. if (!_disposed)
  502. {
  503. if (disposing)
  504. {
  505. _configurationManager.ConfigurationUpdated -= ConfigurationUpdated;
  506. NetworkChange.NetworkAddressChanged -= OnNetworkAddressChanged;
  507. NetworkChange.NetworkAvailabilityChanged -= OnNetworkAvailabilityChanged;
  508. }
  509. _disposed = true;
  510. }
  511. }
  512. private void ConfigurationUpdated(object? sender, EventArgs args)
  513. {
  514. UpdateSettings(_configurationManager.GetNetworkConfiguration());
  515. }
  516. /// <summary>
  517. /// Converts an IPAddress into a string.
  518. /// Ipv6 addresses are returned in [ ], with their scope removed.
  519. /// </summary>
  520. /// <param name="address">Address to convert.</param>
  521. /// <returns>URI save conversion of the address.</returns>
  522. private string FormatIP6String(IPAddress address)
  523. {
  524. var str = address.ToString();
  525. if (address.AddressFamily == AddressFamily.InterNetworkV6)
  526. {
  527. int i = str.IndexOf("%", StringComparison.OrdinalIgnoreCase);
  528. if (i != -1)
  529. {
  530. str = str.Substring(0, i);
  531. }
  532. return $"[{str}]";
  533. }
  534. return str;
  535. }
  536. /// <summary>
  537. /// Checks the string to see if it matches any interface names.
  538. /// </summary>
  539. /// <param name="token">String to check.</param>
  540. /// <param name="index">Interface index number.</param>
  541. /// <returns>True if an interface name matches the token.</returns>
  542. private bool IsInterface(string token, out int index)
  543. {
  544. index = -1;
  545. // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
  546. // Null check required here for automated testing.
  547. if (_interfaceNames != null && token.Length > 1)
  548. {
  549. bool partial = token[^1] == '*';
  550. if (partial)
  551. {
  552. token = token[0..^1];
  553. }
  554. foreach ((string interfc, int interfcIndex) in _interfaceNames)
  555. {
  556. if ((!partial && string.Equals(interfc, token, StringComparison.OrdinalIgnoreCase)) ||
  557. (partial && interfc.StartsWith(token, true, CultureInfo.InvariantCulture)))
  558. {
  559. index = interfcIndex;
  560. return true;
  561. }
  562. }
  563. }
  564. return false;
  565. }
  566. /// <summary>
  567. /// Parses strings into the collection, replacing any interface references.
  568. /// </summary>
  569. /// <param name="col">Collection.</param>
  570. /// <param name="token">String to parse.</param>
  571. private void AddToCollection(NetCollection col, string token)
  572. {
  573. // Is it the name of an interface (windows) eg, Wireless LAN adapter Wireless Network Connection 1.
  574. // Null check required here for automated testing.
  575. if (IsInterface(token, out int index))
  576. {
  577. _logger.LogInformation("Interface {0} used in settings. Using its interface addresses.", token);
  578. // Replace interface tags with the interface IP's.
  579. foreach (IPNetAddress iface in _interfaceAddresses)
  580. {
  581. if (Math.Abs(iface.Tag) == index &&
  582. ((IsIP4Enabled && iface.Address.AddressFamily == AddressFamily.InterNetwork) ||
  583. (IsIP6Enabled && iface.Address.AddressFamily == AddressFamily.InterNetworkV6)))
  584. {
  585. col.Add(iface);
  586. }
  587. }
  588. }
  589. else if (NetCollection.TryParse(token, out IPObject obj))
  590. {
  591. if (!IsIP6Enabled)
  592. {
  593. // Remove IP6 addresses from multi-homed IPHosts.
  594. obj.Remove(AddressFamily.InterNetworkV6);
  595. if (!obj.IsIP6())
  596. {
  597. col.Add(obj);
  598. }
  599. }
  600. else if (!IsIP4Enabled)
  601. {
  602. // Remove IP4 addresses from multi-homed IPHosts.
  603. obj.Remove(AddressFamily.InterNetwork);
  604. if (obj.IsIP6())
  605. {
  606. col.Add(obj);
  607. }
  608. }
  609. else
  610. {
  611. col.Add(obj);
  612. }
  613. }
  614. else
  615. {
  616. _logger.LogDebug("Invalid or unknown network {0}.", token);
  617. }
  618. }
  619. /// <summary>
  620. /// Handler for network change events.
  621. /// </summary>
  622. /// <param name="sender">Sender.</param>
  623. /// <param name="e">Network availability information.</param>
  624. private void OnNetworkAvailabilityChanged(object? sender, NetworkAvailabilityEventArgs e)
  625. {
  626. _logger.LogDebug("Network availability changed.");
  627. OnNetworkChanged();
  628. }
  629. /// <summary>
  630. /// Handler for network change events.
  631. /// </summary>
  632. /// <param name="sender">Sender.</param>
  633. /// <param name="e">Event arguments.</param>
  634. private void OnNetworkAddressChanged(object? sender, EventArgs e)
  635. {
  636. _logger.LogDebug("Network address change detected.");
  637. OnNetworkChanged();
  638. }
  639. /// <summary>
  640. /// Async task that waits for 2 seconds before re-initialising the settings, as typically these events fire multiple times in succession.
  641. /// </summary>
  642. /// <returns>The network change async.</returns>
  643. private async Task OnNetworkChangeAsync()
  644. {
  645. try
  646. {
  647. await Task.Delay(2000).ConfigureAwait(false);
  648. InitialiseInterfaces();
  649. // Recalculate LAN caches.
  650. InitialiseLAN(_configurationManager.GetNetworkConfiguration());
  651. NetworkChanged?.Invoke(this, EventArgs.Empty);
  652. }
  653. finally
  654. {
  655. _eventfire = false;
  656. }
  657. }
  658. /// <summary>
  659. /// Triggers our event, and re-loads interface information.
  660. /// </summary>
  661. private void OnNetworkChanged()
  662. {
  663. lock (_eventFireLock)
  664. {
  665. if (!_eventfire)
  666. {
  667. _logger.LogDebug("Network Address Change Event.");
  668. // As network events tend to fire one after the other only fire once every second.
  669. _eventfire = true;
  670. OnNetworkChangeAsync().GetAwaiter().GetResult();
  671. }
  672. }
  673. }
  674. /// <summary>
  675. /// Parses the user defined overrides into the dictionary object.
  676. /// Overrides are the equivalent of localised publishedServerUrl, enabling
  677. /// different addresses to be advertised over different subnets.
  678. /// format is subnet=ipaddress|host|uri
  679. /// when subnet = 0.0.0.0, any external address matches.
  680. /// </summary>
  681. private void InitialiseOverrides(NetworkConfiguration config)
  682. {
  683. lock (_intLock)
  684. {
  685. _publishedServerUrls.Clear();
  686. string[] overrides = config.PublishedServerUriBySubnet;
  687. if (overrides == null)
  688. {
  689. return;
  690. }
  691. foreach (var entry in overrides)
  692. {
  693. var parts = entry.Split('=');
  694. if (parts.Length != 2)
  695. {
  696. _logger.LogError("Unable to parse bind override. {0}", entry);
  697. }
  698. else
  699. {
  700. var replacement = parts[1].Trim();
  701. if (string.Equals(parts[0], "remaining", StringComparison.OrdinalIgnoreCase))
  702. {
  703. _publishedServerUrls[new IPNetAddress(IPAddress.Broadcast)] = replacement;
  704. }
  705. else if (string.Equals(parts[0], "external", StringComparison.OrdinalIgnoreCase))
  706. {
  707. _publishedServerUrls[new IPNetAddress(IPAddress.Any)] = replacement;
  708. }
  709. else if (TryParseInterface(parts[0], out NetCollection? addresses) && addresses != null)
  710. {
  711. foreach (IPNetAddress na in addresses)
  712. {
  713. _publishedServerUrls[na] = replacement;
  714. }
  715. }
  716. else if (IPNetAddress.TryParse(parts[0], out IPNetAddress result))
  717. {
  718. _publishedServerUrls[result] = replacement;
  719. }
  720. else
  721. {
  722. _logger.LogError("Unable to parse bind ip address. {0}", parts[1]);
  723. }
  724. }
  725. }
  726. }
  727. }
  728. private void InitialiseBind(NetworkConfiguration config)
  729. {
  730. string[] lanAddresses = config.LocalNetworkAddresses;
  731. // TODO: remove when bug fixed: https://github.com/jellyfin/jellyfin-web/issues/1334
  732. if (lanAddresses.Length == 1 && lanAddresses[0].IndexOf(',', StringComparison.OrdinalIgnoreCase) != -1)
  733. {
  734. lanAddresses = lanAddresses[0].Split(',');
  735. }
  736. // TODO: end fix: https://github.com/jellyfin/jellyfin-web/issues/1334
  737. // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded.
  738. if (config.IgnoreVirtualInterfaces)
  739. {
  740. var newList = lanAddresses.ToList();
  741. newList.AddRange(config.VirtualInterfaceNames.Split(',').ToList());
  742. lanAddresses = newList.ToArray();
  743. }
  744. // Read and parse bind addresses and exclusions, removing ones that don't exist.
  745. _bindAddresses = CreateIPCollection(lanAddresses).Union(_interfaceAddresses);
  746. _bindExclusions = CreateIPCollection(lanAddresses, true).Union(_interfaceAddresses);
  747. _logger.LogInformation("Using bind addresses: {0}", _bindAddresses);
  748. _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions);
  749. }
  750. private void InitialiseRemote(NetworkConfiguration config)
  751. {
  752. RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter);
  753. }
  754. /// <summary>
  755. /// Initialises internal LAN cache settings.
  756. /// </summary>
  757. private void InitialiseLAN(NetworkConfiguration config)
  758. {
  759. lock (_intLock)
  760. {
  761. _logger.LogDebug("Refreshing LAN information.");
  762. // Get config options.
  763. string[] subnets = config.LocalNetworkSubnets;
  764. // Create lists from user settings.
  765. _lanSubnets = CreateIPCollection(subnets);
  766. _excludedSubnets = NetCollection.AsNetworks(CreateIPCollection(subnets, true));
  767. // If no LAN addresses are specified - all private subnets are deemed to be the LAN
  768. _usingPrivateAddresses = _lanSubnets.Count == 0;
  769. // NOTE: The order of the commands in this statement matters.
  770. if (_usingPrivateAddresses)
  771. {
  772. _logger.LogDebug("Using LAN interface addresses as user provided no LAN details.");
  773. // Internal interfaces must be private and not excluded.
  774. _internalInterfaces = new NetCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.Contains(i)));
  775. // Subnets are the same as the calculated internal interface.
  776. _lanSubnets = new NetCollection();
  777. // We must listen on loopback for LiveTV to function regardless of the settings.
  778. if (IsIP6Enabled)
  779. {
  780. _lanSubnets.Add(IPNetAddress.IP6Loopback);
  781. _lanSubnets.Add(IPNetAddress.Parse("fc00::/7")); // ULA
  782. _lanSubnets.Add(IPNetAddress.Parse("fe80::/10")); // Site local
  783. }
  784. if (IsIP4Enabled)
  785. {
  786. _lanSubnets.Add(IPNetAddress.IP4Loopback);
  787. _lanSubnets.Add(IPNetAddress.Parse("10.0.0.0/8"));
  788. _lanSubnets.Add(IPNetAddress.Parse("172.16.0.0/12"));
  789. _lanSubnets.Add(IPNetAddress.Parse("192.168.0.0/16"));
  790. }
  791. }
  792. else
  793. {
  794. // We must listen on loopback for LiveTV to function regardless of the settings.
  795. if (IsIP6Enabled)
  796. {
  797. _lanSubnets.Add(IPNetAddress.IP6Loopback);
  798. }
  799. if (IsIP4Enabled)
  800. {
  801. _lanSubnets.Add(IPNetAddress.IP4Loopback);
  802. }
  803. // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet.
  804. _internalInterfaces = new NetCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i) && !_excludedSubnets.Contains(i) && _lanSubnets.Contains(i)));
  805. }
  806. _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets);
  807. _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets);
  808. _logger.LogInformation("Using LAN addresses: {0}", NetCollection.AsNetworks(_lanSubnets.Exclude(_excludedSubnets)));
  809. }
  810. }
  811. /// <summary>
  812. /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state.
  813. /// Generate a list of all active mac addresses that aren't loopback addresses.
  814. /// </summary>
  815. private void InitialiseInterfaces()
  816. {
  817. lock (_intLock)
  818. {
  819. _logger.LogDebug("Refreshing interfaces.");
  820. _interfaceNames.Clear();
  821. _interfaceAddresses.Clear();
  822. try
  823. {
  824. IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces()
  825. .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up);
  826. foreach (NetworkInterface adapter in nics)
  827. {
  828. try
  829. {
  830. IPInterfaceProperties ipProperties = adapter.GetIPProperties();
  831. PhysicalAddress mac = adapter.GetPhysicalAddress();
  832. // populate mac list
  833. if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac != null && mac != PhysicalAddress.None)
  834. {
  835. _macAddresses.Add(mac);
  836. }
  837. // populate interface address list
  838. foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses)
  839. {
  840. if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork)
  841. {
  842. IPNetAddress nw = new IPNetAddress(info.Address, info.IPv4Mask)
  843. {
  844. // Keep the number of gateways on this interface, along with its index.
  845. Tag = ipProperties.GetIPv4Properties().Index
  846. };
  847. int tag = nw.Tag;
  848. if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback())
  849. {
  850. // -ve Tags signify the interface has a gateway.
  851. nw.Tag *= -1;
  852. }
  853. _interfaceAddresses.Add(nw);
  854. // Store interface name so we can use the name in Collections.
  855. _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
  856. _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
  857. }
  858. else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6)
  859. {
  860. IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength)
  861. {
  862. // Keep the number of gateways on this interface, along with its index.
  863. Tag = ipProperties.GetIPv6Properties().Index
  864. };
  865. int tag = nw.Tag;
  866. if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback())
  867. {
  868. // -ve Tags signify the interface has a gateway.
  869. nw.Tag *= -1;
  870. }
  871. _interfaceAddresses.Add(nw);
  872. // Store interface name so we can use the name in Collections.
  873. _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
  874. _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
  875. }
  876. }
  877. }
  878. #pragma warning disable CA1031 // Do not catch general exception types
  879. catch
  880. {
  881. // Ignore error, and attempt to continue.
  882. }
  883. #pragma warning restore CA1031 // Do not catch general exception types
  884. }
  885. _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count);
  886. _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses);
  887. // If for some reason we don't have an interface info, resolve our DNS name.
  888. if (_interfaceAddresses.Count == 0)
  889. {
  890. _logger.LogWarning("No interfaces information available. Using loopback.");
  891. IPHost host = new IPHost(Dns.GetHostName());
  892. foreach (var a in host.GetAddresses())
  893. {
  894. _interfaceAddresses.Add(a);
  895. }
  896. if (_interfaceAddresses.Count == 0)
  897. {
  898. _logger.LogError("No interfaces information available. Resolving DNS name.");
  899. // Last ditch attempt - use loopback address.
  900. _interfaceAddresses.Add(IPNetAddress.IP4Loopback);
  901. if (IsIP6Enabled)
  902. {
  903. _interfaceAddresses.Add(IPNetAddress.IP6Loopback);
  904. }
  905. }
  906. }
  907. }
  908. catch (NetworkInformationException ex)
  909. {
  910. _logger.LogError(ex, "Error in InitialiseInterfaces.");
  911. }
  912. }
  913. }
  914. /// <summary>
  915. /// Attempts to match the source against a user defined bind interface.
  916. /// </summary>
  917. /// <param name="source">IP source address to use.</param>
  918. /// <param name="isExternal">True if the source is in the external subnet.</param>
  919. /// <param name="bindPreference">The published server url that matches the source address.</param>
  920. /// <param name="port">The resultant port, if one exists.</param>
  921. /// <returns>True if a match is found.</returns>
  922. private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, out string bindPreference, out int? port)
  923. {
  924. bindPreference = string.Empty;
  925. port = null;
  926. // Check for user override.
  927. foreach (var addr in _publishedServerUrls)
  928. {
  929. // Remaining. Match anything.
  930. if (addr.Key.Equals(IPAddress.Broadcast))
  931. {
  932. bindPreference = addr.Value;
  933. break;
  934. }
  935. else if ((addr.Key.Equals(IPAddress.Any) || addr.Key.Equals(IPAddress.IPv6Any)) && isExternal)
  936. {
  937. // External.
  938. bindPreference = addr.Value;
  939. break;
  940. }
  941. else if (addr.Key.Contains(source))
  942. {
  943. // Match ip address.
  944. bindPreference = addr.Value;
  945. break;
  946. }
  947. }
  948. if (!string.IsNullOrEmpty(bindPreference))
  949. {
  950. // Has it got a port defined?
  951. var parts = bindPreference.Split(':');
  952. if (parts.Length > 1)
  953. {
  954. if (int.TryParse(parts[1], out int p))
  955. {
  956. bindPreference = parts[0];
  957. port = p;
  958. }
  959. }
  960. return true;
  961. }
  962. return false;
  963. }
  964. /// <summary>
  965. /// Attempts to match the source against a user defined bind interface.
  966. /// </summary>
  967. /// <param name="source">IP source address to use.</param>
  968. /// <param name="isExternal">True if the source is in the external subnet.</param>
  969. /// <param name="result">The result, if a match is found.</param>
  970. /// <returns>True if a match is found.</returns>
  971. private bool MatchesBindInterface(IPObject source, bool isExternal, out string result)
  972. {
  973. result = string.Empty;
  974. var nc = _bindAddresses.Exclude(_bindExclusions);
  975. int count = nc.Count;
  976. if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any)))
  977. {
  978. // Ignore IPAny addresses.
  979. count = 0;
  980. }
  981. if (count != 0)
  982. {
  983. // Check to see if any of the bind interfaces are in the same subnet.
  984. NetCollection bindResult;
  985. IPAddress? defaultGateway = null;
  986. IPAddress? bindAddress;
  987. if (isExternal)
  988. {
  989. // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first.
  990. bindResult = new NetCollection(nc
  991. .Where(p => !IsInLocalNetwork(p))
  992. .OrderBy(p => p.Tag));
  993. defaultGateway = bindResult.FirstOrDefault()?.Address;
  994. bindAddress = bindResult
  995. .Where(p => p.Contains(source))
  996. .OrderBy(p => p.Tag)
  997. .FirstOrDefault()?.Address;
  998. }
  999. else
  1000. {
  1001. // Look for the best internal address.
  1002. bindAddress = nc
  1003. .Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None)))
  1004. .OrderBy(p => p.Tag)
  1005. .FirstOrDefault()?.Address;
  1006. }
  1007. if (bindAddress != null)
  1008. {
  1009. result = FormatIP6String(bindAddress);
  1010. _logger.LogDebug("{0}: GetBindInterface: Has source, found a match bind interface subnets. {1}", source, result);
  1011. return true;
  1012. }
  1013. if (isExternal && defaultGateway != null)
  1014. {
  1015. result = FormatIP6String(defaultGateway);
  1016. _logger.LogDebug("{0}: GetBindInterface: Using first user defined external interface. {1}", source, result);
  1017. return true;
  1018. }
  1019. result = FormatIP6String(nc.First().Address);
  1020. _logger.LogDebug("{0}: GetBindInterface: Selected first user defined interface. {1}", source, result);
  1021. if (isExternal)
  1022. {
  1023. // TODO: remove this after testing.
  1024. _logger.LogWarning("{0}: External request received, however, only an internal interface bind found.", source);
  1025. }
  1026. return true;
  1027. }
  1028. return false;
  1029. }
  1030. /// <summary>
  1031. /// Attempts to match the source against an external interface.
  1032. /// </summary>
  1033. /// <param name="source">IP source address to use.</param>
  1034. /// <param name="result">The result, if a match is found.</param>
  1035. /// <returns>True if a match is found.</returns>
  1036. private bool MatchesExternalInterface(IPObject source, out string result)
  1037. {
  1038. result = string.Empty;
  1039. // Get the first WAN interface address that isn't a loopback.
  1040. var extResult = new NetCollection(_interfaceAddresses
  1041. .Exclude(_bindExclusions)
  1042. .Where(p => !IsInLocalNetwork(p))
  1043. .OrderBy(p => p.Tag));
  1044. if (extResult.Count > 0)
  1045. {
  1046. // Does the request originate in one of the interface subnets?
  1047. // (For systems with multiple internal network cards, and multiple subnets)
  1048. foreach (var intf in extResult)
  1049. {
  1050. if (!IsInLocalNetwork(intf) && intf.Contains(source))
  1051. {
  1052. result = FormatIP6String(intf.Address);
  1053. _logger.LogDebug("{0}: GetBindInterface: Selected best external on interface on range. {1}", source, result);
  1054. return true;
  1055. }
  1056. }
  1057. result = FormatIP6String(extResult.First().Address);
  1058. _logger.LogDebug("{0}: GetBindInterface: Selected first external interface. {0}", source, result);
  1059. return true;
  1060. }
  1061. // Have to return something, so return an internal address
  1062. // TODO: remove this after testing.
  1063. _logger.LogWarning("{0}: External request received, however, no WAN interface found.", source);
  1064. return false;
  1065. }
  1066. }
  1067. }