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