NetworkManager.cs 48 KB

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