NetworkManager.cs 51 KB

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