NetworkManager.cs 53 KB

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