NetworkManager.cs 51 KB

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