NetworkManager.cs 51 KB

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