HttpsScanMiddleware.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using Microsoft.Extensions.DependencyInjection;
  2. using Microsoft.Extensions.Logging;
  3. using Microsoft.Extensions.Options;
  4. using System;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace FastGithub.Scanner.Middlewares
  10. {
  11. [Service(ServiceLifetime.Singleton)]
  12. sealed class HttpsScanMiddleware : IGithubScanMiddleware
  13. {
  14. private readonly IOptionsMonitor<GithubOptions> options;
  15. private readonly ILogger<HttpsScanMiddleware> logger;
  16. public HttpsScanMiddleware(
  17. IOptionsMonitor<GithubOptions> options,
  18. ILogger<HttpsScanMiddleware> logger)
  19. {
  20. this.options = options;
  21. this.logger = logger;
  22. }
  23. public async Task InvokeAsync(GithubContext context, Func<Task> next)
  24. {
  25. try
  26. {
  27. var request = new HttpRequestMessage
  28. {
  29. Method = HttpMethod.Get,
  30. RequestUri = new Uri($"https://{context.Address}"),
  31. };
  32. request.Headers.Host = context.Domain;
  33. using var httpClient = new HttpClient(new HttpClientHandler
  34. {
  35. Proxy = null,
  36. UseProxy = false,
  37. });
  38. var startTime = DateTime.Now;
  39. using var cancellationTokenSource = new CancellationTokenSource(this.options.CurrentValue.HttpsScanTimeout);
  40. var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationTokenSource.Token);
  41. var server = response.EnsureSuccessStatusCode().Headers.Server;
  42. if (server.Any(s => string.Equals("GitHub.com", s.Product?.Name, StringComparison.OrdinalIgnoreCase)))
  43. {
  44. context.HttpElapsed = DateTime.Now.Subtract(startTime);
  45. await next();
  46. }
  47. }
  48. catch (TaskCanceledException)
  49. {
  50. this.logger.LogTrace($"{context.Domain} {context.Address}连接超时");
  51. }
  52. catch (Exception ex)
  53. {
  54. this.logger.LogTrace($"{context.Domain} {context.Address} {ex.Message}");
  55. }
  56. }
  57. }
  58. }