NetworkManager.cs 51 KB

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