NetworkManager.cs 51 KB

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