NetworkManager.cs 51 KB

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