TcpScanMiddleware.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using Microsoft.Extensions.Caching.Memory;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using Microsoft.Extensions.Logging;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Net.Sockets;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace FastGithub.Scanner.ScanMiddlewares
  10. {
  11. /// <summary>
  12. /// tcp扫描中间件
  13. /// </summary>
  14. [Service(ServiceLifetime.Singleton)]
  15. sealed class TcpScanMiddleware : IMiddleware<GithubContext>
  16. {
  17. private const int PORT = 443;
  18. private readonly TimeSpan cacheTimeSpan = TimeSpan.FromMinutes(20d);
  19. private readonly IOptionsMonitor<GithubOptions> options;
  20. private readonly IMemoryCache memoryCache;
  21. private readonly ILogger<TcpScanMiddleware> logger;
  22. /// <summary>
  23. /// tcp扫描中间件
  24. /// </summary>
  25. /// <param name="options"></param>
  26. /// <param name="logger"></param>
  27. public TcpScanMiddleware(
  28. IOptionsMonitor<GithubOptions> options,
  29. IMemoryCache memoryCache,
  30. ILogger<TcpScanMiddleware> logger)
  31. {
  32. this.options = options;
  33. this.memoryCache = memoryCache;
  34. this.logger = logger;
  35. }
  36. /// <summary>
  37. /// tcp扫描
  38. /// </summary>
  39. /// <param name="context"></param>
  40. /// <param name="next"></param>
  41. /// <returns></returns>
  42. public async Task InvokeAsync(GithubContext context, Func<Task> next)
  43. {
  44. var key = $"tcp://{context.Address}";
  45. if (this.memoryCache.TryGetValue<bool>(key, out var available) == false)
  46. {
  47. available = await this.TcpScanAsync(context);
  48. this.memoryCache.Set(key, available, cacheTimeSpan);
  49. }
  50. if (available == true)
  51. {
  52. await next();
  53. }
  54. else
  55. {
  56. this.logger.LogTrace($"{context.Domain} {context.Address}的{PORT}端口未开放");
  57. }
  58. }
  59. /// <summary>
  60. /// tcp扫描
  61. /// </summary>
  62. /// <param name="context"></param>
  63. /// <returns></returns>
  64. private async Task<bool> TcpScanAsync(GithubContext context)
  65. {
  66. try
  67. {
  68. using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  69. var timeout = this.options.CurrentValue.Scan.TcpScanTimeout;
  70. using var cancellationTokenSource = new CancellationTokenSource(timeout);
  71. await socket.ConnectAsync(context.Address, PORT, cancellationTokenSource.Token);
  72. return true;
  73. }
  74. catch (Exception)
  75. {
  76. return false;
  77. }
  78. }
  79. }
  80. }