NetworkManager.cs 52 KB

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