NetworkManager.cs 53 KB

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