NetworkManager.cs 52 KB

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