NetworkManager.cs 47 KB

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