NetworkManager.cs 49 KB

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