NetworkManager.cs 47 KB

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