NetworkManager.cs 49 KB

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