NetworkManager.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  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[] lanAddresses = config.LocalNetworkAddresses;
  759. // TODO: remove when bug fixed: https://github.com/jellyfin/jellyfin-web/issues/1334
  760. if (lanAddresses.Length == 1 && lanAddresses[0].IndexOf(',', StringComparison.OrdinalIgnoreCase) != -1)
  761. {
  762. lanAddresses = lanAddresses[0].Split(',');
  763. }
  764. // TODO: end fix.
  765. // TODO: end fix.
  766. // Add virtual machine interface names to the list of bind exclusions, so that they are auto-excluded.
  767. if (config.IgnoreVirtualInterfaces)
  768. {
  769. var newList = lanAddresses.ToList();
  770. newList.AddRange(config.VirtualInterfaceNames.Split(',').ToList());
  771. lanAddresses = newList.ToArray();
  772. }
  773. // Read and parse bind addresses and exclusions, removing ones that don't exist.
  774. _bindAddresses = CreateIPCollection(lanAddresses).Union(_interfaceAddresses);
  775. _bindExclusions = CreateIPCollection(lanAddresses, true).Union(_interfaceAddresses);
  776. _logger.LogInformation("Using bind addresses: {0}", _bindAddresses);
  777. _logger.LogInformation("Using bind exclusions: {0}", _bindExclusions);
  778. }
  779. private void InitialiseRemote(NetworkConfiguration config)
  780. {
  781. RemoteAddressFilter = CreateIPCollection(config.RemoteIPFilter);
  782. }
  783. /// <summary>
  784. /// Initialises internal LAN cache settings.
  785. /// </summary>
  786. private void InitialiseLAN(NetworkConfiguration config)
  787. {
  788. lock (_intLock)
  789. {
  790. _logger.LogDebug("Refreshing LAN information.");
  791. // Get config options.
  792. string[] subnets = config.LocalNetworkSubnets;
  793. // Create lists from user settings.
  794. _lanSubnets = CreateIPCollection(subnets);
  795. _excludedSubnets = NetCollection.AsNetworks(CreateIPCollection(subnets, true));
  796. // If no LAN addresses are specified - all private subnets are deemed to be the LAN
  797. _usingPrivateAddresses = _lanSubnets.Count == 0;
  798. // NOTE: The order of the commands in this statement matters, otherwise the lists won't initialise correctly.
  799. if (_usingPrivateAddresses)
  800. {
  801. _logger.LogDebug("Using LAN interface addresses as user provided no LAN details.");
  802. // Internal interfaces must be private and not excluded.
  803. _internalInterfaces = new NetCollection(_interfaceAddresses.Where(i => IsPrivateAddressRange(i) && !_excludedSubnets.Contains(i)));
  804. // Subnets are the same as the calculated internal interface.
  805. _lanSubnets = new NetCollection();
  806. // We must listen on loopback for LiveTV to function regardless of the settings.
  807. if (IsIP6Enabled)
  808. {
  809. _lanSubnets.Add(IPNetAddress.IP6Loopback);
  810. _lanSubnets.Add(IPNetAddress.Parse("fc00::/7")); // ULA
  811. _lanSubnets.Add(IPNetAddress.Parse("fe80::/10")); // Site local
  812. }
  813. if (IsIP4Enabled)
  814. {
  815. _lanSubnets.Add(IPNetAddress.IP4Loopback);
  816. _lanSubnets.Add(IPNetAddress.Parse("10.0.0.0/8"));
  817. _lanSubnets.Add(IPNetAddress.Parse("172.16.0.0/12"));
  818. _lanSubnets.Add(IPNetAddress.Parse("192.168.0.0/16"));
  819. }
  820. }
  821. else
  822. {
  823. // We must listen on loopback for LiveTV to function regardless of the settings.
  824. if (IsIP6Enabled)
  825. {
  826. _lanSubnets.Add(IPNetAddress.IP6Loopback);
  827. }
  828. if (IsIP4Enabled)
  829. {
  830. _lanSubnets.Add(IPNetAddress.IP4Loopback);
  831. }
  832. // Internal interfaces must be private, not excluded and part of the LocalNetworkSubnet.
  833. _internalInterfaces = new NetCollection(_interfaceAddresses.Where(i => IsInLocalNetwork(i) && !_excludedSubnets.Contains(i) && _lanSubnets.Contains(i)));
  834. }
  835. _logger.LogInformation("Defined LAN addresses : {0}", _lanSubnets);
  836. _logger.LogInformation("Defined LAN exclusions : {0}", _excludedSubnets);
  837. _logger.LogInformation("Using LAN addresses: {0}", NetCollection.AsNetworks(_lanSubnets.Exclude(_excludedSubnets)));
  838. }
  839. }
  840. /// <summary>
  841. /// Generate a list of all the interface ip addresses and submasks where that are in the active/unknown state.
  842. /// Generate a list of all active mac addresses that aren't loopback addreses.
  843. /// </summary>
  844. private void InitialiseInterfaces()
  845. {
  846. lock (_intLock)
  847. {
  848. _logger.LogDebug("Refreshing interfaces.");
  849. _interfaceNames.Clear();
  850. _interfaceAddresses.Clear();
  851. try
  852. {
  853. IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces()
  854. .Where(i => i.SupportsMulticast && i.OperationalStatus == OperationalStatus.Up);
  855. foreach (NetworkInterface adapter in nics)
  856. {
  857. try
  858. {
  859. IPInterfaceProperties ipProperties = adapter.GetIPProperties();
  860. PhysicalAddress mac = adapter.GetPhysicalAddress();
  861. // populate mac list
  862. if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback && mac != null && mac != PhysicalAddress.None)
  863. {
  864. _macAddresses.Add(mac);
  865. }
  866. // populate interface address list
  867. foreach (UnicastIPAddressInformation info in ipProperties.UnicastAddresses)
  868. {
  869. if (IsIP4Enabled && info.Address.AddressFamily == AddressFamily.InterNetwork)
  870. {
  871. IPNetAddress nw = new IPNetAddress(info.Address, info.IPv4Mask)
  872. {
  873. // Keep the number of gateways on this interface, along with its index.
  874. Tag = ipProperties.GetIPv4Properties().Index
  875. };
  876. int tag = nw.Tag;
  877. if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback())
  878. {
  879. // -ve Tags signify the interface has a gateway.
  880. nw.Tag *= -1;
  881. }
  882. _interfaceAddresses.Add(nw);
  883. // Store interface name so we can use the name in Collections.
  884. _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
  885. _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
  886. }
  887. else if (IsIP6Enabled && info.Address.AddressFamily == AddressFamily.InterNetworkV6)
  888. {
  889. IPNetAddress nw = new IPNetAddress(info.Address, (byte)info.PrefixLength)
  890. {
  891. // Keep the number of gateways on this interface, along with its index.
  892. Tag = ipProperties.GetIPv6Properties().Index
  893. };
  894. int tag = nw.Tag;
  895. if ((ipProperties.GatewayAddresses.Count > 0) && !nw.IsLoopback())
  896. {
  897. // -ve Tags signify the interface has a gateway.
  898. nw.Tag *= -1;
  899. }
  900. _interfaceAddresses.Add(nw);
  901. // Store interface name so we can use the name in Collections.
  902. _interfaceNames[adapter.Description.ToLower(CultureInfo.InvariantCulture)] = tag;
  903. _interfaceNames["eth" + tag.ToString(CultureInfo.InvariantCulture)] = tag;
  904. }
  905. }
  906. }
  907. #pragma warning disable CA1031 // Do not catch general exception types
  908. catch
  909. {
  910. // Ignore error, and attempt to continue.
  911. }
  912. #pragma warning restore CA1031 // Do not catch general exception types
  913. }
  914. _logger.LogDebug("Discovered {0} interfaces.", _interfaceAddresses.Count);
  915. _logger.LogDebug("Interfaces addresses : {0}", _interfaceAddresses);
  916. // If for some reason we don't have an interface info, resolve our DNS name.
  917. if (_interfaceAddresses.Count == 0)
  918. {
  919. _logger.LogWarning("No interfaces information available. Using loopback.");
  920. IPHost host = new IPHost(Dns.GetHostName());
  921. foreach (var a in host.GetAddresses())
  922. {
  923. _interfaceAddresses.Add(a);
  924. }
  925. if (_interfaceAddresses.Count == 0)
  926. {
  927. _logger.LogError("No interfaces information available. Resolving DNS name.");
  928. // Last ditch attempt - use loopback address.
  929. _interfaceAddresses.Add(IPNetAddress.IP4Loopback);
  930. if (IsIP6Enabled)
  931. {
  932. _interfaceAddresses.Add(IPNetAddress.IP6Loopback);
  933. }
  934. }
  935. }
  936. }
  937. catch (NetworkInformationException ex)
  938. {
  939. _logger.LogError(ex, "Error in InitialiseInterfaces.");
  940. }
  941. }
  942. }
  943. /// <summary>
  944. /// Attempts to match the source against a user defined bind interface.
  945. /// </summary>
  946. /// <param name="source">IP source address to use.</param>
  947. /// <param name="isExternal">True if the source is in the external subnet.</param>
  948. /// <param name="bindPreference">The published server url that matches the source address.</param>
  949. /// <param name="port">The resultant port, if one exists.</param>
  950. /// <returns>True if a match is found.</returns>
  951. private bool MatchesPublishedServerUrl(IPObject source, bool isExternal, out string bindPreference, out int? port)
  952. {
  953. bindPreference = string.Empty;
  954. port = null;
  955. // Check for user override.
  956. foreach (var addr in _publishedServerUrls)
  957. {
  958. // Remaining. Match anything.
  959. if (addr.Key.Equals(IPAddress.Broadcast))
  960. {
  961. bindPreference = addr.Value;
  962. break;
  963. }
  964. else if ((addr.Key.Equals(IPAddress.Any) || addr.Key.Equals(IPAddress.IPv6Any)) && isExternal)
  965. {
  966. // External.
  967. bindPreference = addr.Value;
  968. break;
  969. }
  970. else if (addr.Key.Contains(source))
  971. {
  972. // Match ip address.
  973. bindPreference = addr.Value;
  974. break;
  975. }
  976. }
  977. if (!string.IsNullOrEmpty(bindPreference))
  978. {
  979. // Has it got a port defined?
  980. var parts = bindPreference.Split(':');
  981. if (parts.Length > 1)
  982. {
  983. if (int.TryParse(parts[1], out int p))
  984. {
  985. bindPreference = parts[0];
  986. port = p;
  987. }
  988. }
  989. return true;
  990. }
  991. return false;
  992. }
  993. /// <summary>
  994. /// Attempts to match the source against a user defined bind interface.
  995. /// </summary>
  996. /// <param name="source">IP source address to use.</param>
  997. /// <param name="isExternal">True if the source is in the external subnet.</param>
  998. /// <param name="result">The result, if a match is found.</param>
  999. /// <returns>True if a match is found.</returns>
  1000. private bool MatchesBindInterface(IPObject source, bool isExternal, out string result)
  1001. {
  1002. result = string.Empty;
  1003. var nc = _bindAddresses.Exclude(_bindExclusions);
  1004. int count = nc.Count;
  1005. if (count == 1 && (_bindAddresses[0].Equals(IPAddress.Any) || _bindAddresses[0].Equals(IPAddress.IPv6Any)))
  1006. {
  1007. // Ignore IPAny addresses.
  1008. count = 0;
  1009. }
  1010. if (count != 0)
  1011. {
  1012. // Check to see if any of the bind interfaces are in the same subnet.
  1013. NetCollection bindResult;
  1014. IPAddress? defaultGateway = null;
  1015. IPAddress? bindAddress;
  1016. if (isExternal)
  1017. {
  1018. // Find all external bind addresses. Store the default gateway, but check to see if there is a better match first.
  1019. bindResult = new NetCollection(nc
  1020. .Where(p => !IsInLocalNetwork(p))
  1021. .OrderBy(p => p.Tag));
  1022. defaultGateway = bindResult.FirstOrDefault()?.Address;
  1023. bindAddress = bindResult
  1024. .Where(p => p.Contains(source))
  1025. .OrderBy(p => p.Tag)
  1026. .FirstOrDefault()?.Address;
  1027. }
  1028. else
  1029. {
  1030. // Look for the best internal address.
  1031. bindAddress = nc
  1032. .Where(p => IsInLocalNetwork(p) && (p.Contains(source) || p.Equals(IPAddress.None)))
  1033. .OrderBy(p => p.Tag)
  1034. .FirstOrDefault()?.Address;
  1035. }
  1036. if (bindAddress != null)
  1037. {
  1038. result = FormatIP6String(bindAddress);
  1039. _logger.LogDebug("{0}: GetBindInterface: Has source, found a match bind interface subnets. {1}", source, result);
  1040. return true;
  1041. }
  1042. if (isExternal && defaultGateway != null)
  1043. {
  1044. result = FormatIP6String(defaultGateway);
  1045. _logger.LogDebug("{0}: GetBindInterface: Using first user defined external interface. {1}", source, result);
  1046. return true;
  1047. }
  1048. result = FormatIP6String(nc.First().Address);
  1049. _logger.LogDebug("{0}: GetBindInterface: Selected first user defined interface. {1}", source, result);
  1050. if (isExternal)
  1051. {
  1052. // TODO: remove this after testing.
  1053. _logger.LogWarning("{0}: External request received, however, only an internal interface bind found.", source);
  1054. }
  1055. return true;
  1056. }
  1057. return false;
  1058. }
  1059. /// <summary>
  1060. /// Attempts to match the source against an external interface.
  1061. /// </summary>
  1062. /// <param name="source">IP source address to use.</param>
  1063. /// <param name="result">The result, if a match is found.</param>
  1064. /// <returns>True if a match is found.</returns>
  1065. private bool MatchesExternalInterface(IPObject source, out string result)
  1066. {
  1067. result = string.Empty;
  1068. // Get the first WAN interface address that isn't a loopback.
  1069. var extResult = new NetCollection(_interfaceAddresses
  1070. .Exclude(_bindExclusions)
  1071. .Where(p => !IsInLocalNetwork(p))
  1072. .OrderBy(p => p.Tag));
  1073. if (extResult.Count > 0)
  1074. {
  1075. // Does the request originate in one of the interface subnets?
  1076. // (For systems with multiple internal network cards, and multiple subnets)
  1077. foreach (var intf in extResult)
  1078. {
  1079. if (!IsInLocalNetwork(intf) && intf.Contains(source))
  1080. {
  1081. result = FormatIP6String(intf.Address);
  1082. _logger.LogDebug("{0}: GetBindInterface: Selected best external on interface on range. {1}", source, result);
  1083. return true;
  1084. }
  1085. }
  1086. result = FormatIP6String(extResult.First().Address);
  1087. _logger.LogDebug("{0}: GetBindInterface: Selected first external interface. {0}", source, result);
  1088. return true;
  1089. }
  1090. // Have to return something, so return an internal address
  1091. // TODO: remove this after testing.
  1092. _logger.LogWarning("{0}: External request received, however, no WAN interface found.", source);
  1093. return false;
  1094. }
  1095. }
  1096. }