2
0

NetworkManager.cs 49 KB

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