NetworkManager.cs 48 KB

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