From c86e37172f45cf53b1636bc8fbe9cfb1edc8b6f4 Mon Sep 17 00:00:00 2001 From: xljiulang <366193849@qq.com> Date: Sat, 12 Jun 2021 00:06:48 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=AD=E9=97=B4=E4=BB=B6=E9=87=8D=E5=91=BD?= =?UTF-8?q?=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FastGithub/Middlewares/HttpsScanMiddleware.cs | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 FastGithub/Middlewares/HttpsScanMiddleware.cs diff --git a/FastGithub/Middlewares/HttpsScanMiddleware.cs b/FastGithub/Middlewares/HttpsScanMiddleware.cs new file mode 100644 index 0000000..39ec0c5 --- /dev/null +++ b/FastGithub/Middlewares/HttpsScanMiddleware.cs @@ -0,0 +1,64 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using System; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +namespace FastGithub.Middlewares +{ + sealed class HttpsScanMiddleware : IGithubMiddleware + { + private readonly IOptionsMonitor options; + private readonly ILogger logger; + + public HttpsScanMiddleware( + IOptionsMonitor options, + ILogger logger) + { + this.options = options; + this.logger = logger; + } + + public async Task InvokeAsync(GithubContext context, Func next) + { + try + { + var request = new HttpRequestMessage + { + Method = HttpMethod.Get, + RequestUri = new Uri($"https://{context.Address}"), + }; + request.Headers.Host = context.Domain; + + using var httpClient = new HttpClient(new HttpClientHandler + { + Proxy = null, + UseProxy = false, + ServerCertificateCustomValidationCallback = (_, _, _, _) => true + }); + + var startTime = DateTime.Now; + using var cancellationTokenSource = new CancellationTokenSource(this.options.CurrentValue.HttpsScanTimeout); + var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationTokenSource.Token); + var server = response.EnsureSuccessStatusCode().Headers.Server; + if (server.Any(s => string.Equals("GitHub.com", s.Product?.Name, StringComparison.OrdinalIgnoreCase))) + { + context.HttpElapsed = DateTime.Now.Subtract(startTime); + this.logger.LogWarning(context.ToString()); + + await next(); + } + } + catch (TaskCanceledException) + { + this.logger.LogInformation($"{context.Domain} {context.Address}连接超时"); + } + catch (Exception ex) + { + this.logger.LogInformation($"{context.Domain} {context.Address} {ex.Message}"); + } + } + } +}