NetworkManager.cs 51 KB

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