HttpReverseProxyMiddleware.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. using FastGithub.Configuration;
  2. using FastGithub.Http;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.Extensions.Logging;
  5. using System;
  6. using System.Diagnostics.CodeAnalysis;
  7. using System.Threading.Tasks;
  8. using Yarp.ReverseProxy.Forwarder;
  9. namespace FastGithub.HttpServer
  10. {
  11. /// <summary>
  12. /// 反向代理中间件
  13. /// </summary>
  14. sealed class HttpReverseProxyMiddleware
  15. {
  16. private const string LOOPBACK = "127.0.0.1";
  17. private const string LOCALHOST = "localhost";
  18. private const int HTTP_PORT = 80;
  19. private const int HTTPS_PORT = 443;
  20. private static readonly DomainConfig defaultDomainConfig = new() { TlsSni = true };
  21. private readonly IHttpForwarder httpForwarder;
  22. private readonly IHttpClientFactory httpClientFactory;
  23. private readonly FastGithubConfig fastGithubConfig;
  24. private readonly ILogger<HttpReverseProxyMiddleware> logger;
  25. public HttpReverseProxyMiddleware(
  26. IHttpForwarder httpForwarder,
  27. IHttpClientFactory httpClientFactory,
  28. FastGithubConfig fastGithubConfig,
  29. ILogger<HttpReverseProxyMiddleware> logger)
  30. {
  31. this.httpForwarder = httpForwarder;
  32. this.httpClientFactory = httpClientFactory;
  33. this.fastGithubConfig = fastGithubConfig;
  34. this.logger = logger;
  35. }
  36. /// <summary>
  37. /// 处理请求
  38. /// </summary>
  39. /// <param name="context"></param>
  40. /// <param name="next"?
  41. /// <returns></returns>
  42. public async Task InvokeAsync(HttpContext context, RequestDelegate next)
  43. {
  44. var host = context.Request.Host;
  45. if (this.TryGetDomainConfig(host, out var domainConfig) == false)
  46. {
  47. await next(context);
  48. }
  49. else if (domainConfig.Response == null)
  50. {
  51. var scheme = context.Request.Scheme;
  52. var destinationPrefix = GetDestinationPrefix(scheme, host, domainConfig.Destination);
  53. var httpClient = this.httpClientFactory.CreateHttpClient(host.Host, domainConfig);
  54. var error = await httpForwarder.SendAsync(context, destinationPrefix, httpClient);
  55. await HandleErrorAsync(context, error);
  56. }
  57. else
  58. {
  59. context.Response.StatusCode = domainConfig.Response.StatusCode;
  60. context.Response.ContentType = domainConfig.Response.ContentType;
  61. if (domainConfig.Response.ContentValue != null)
  62. {
  63. await context.Response.WriteAsync(domainConfig.Response.ContentValue);
  64. }
  65. }
  66. }
  67. /// <summary>
  68. /// 获取域名的DomainConfig
  69. /// </summary>
  70. /// <param name="host"></param>
  71. /// <param name="domainConfig"></param>
  72. /// <returns></returns>
  73. private bool TryGetDomainConfig(HostString host, [MaybeNullWhen(false)] out DomainConfig domainConfig)
  74. {
  75. if (this.fastGithubConfig.TryGetDomainConfig(host.Host, out domainConfig) == true)
  76. {
  77. return true;
  78. }
  79. // http(s)://127.0.0.1
  80. // http(s)://localhost
  81. if (host.Host == LOOPBACK || host.Host == LOCALHOST)
  82. {
  83. if (host.Port == null || host.Port == HTTPS_PORT || host.Port == HTTP_PORT)
  84. {
  85. return false;
  86. }
  87. }
  88. // 未配置的域名,但dns污染解析为127.0.0.1的域名
  89. this.logger.LogWarning($"检测到{host.Host}可能遭遇了dns污染");
  90. domainConfig = defaultDomainConfig;
  91. return true;
  92. }
  93. /// <summary>
  94. /// 获取目标前缀
  95. /// </summary>
  96. /// <param name="scheme"></param>
  97. /// <param name="host"></param>
  98. /// <param name="destination"></param>
  99. /// <returns></returns>
  100. private string GetDestinationPrefix(string scheme, HostString host, Uri? destination)
  101. {
  102. var defaultValue = $"{scheme}://{host}/";
  103. if (destination == null)
  104. {
  105. return defaultValue;
  106. }
  107. var baseUri = new Uri(defaultValue);
  108. var result = new Uri(baseUri, destination).ToString();
  109. this.logger.LogInformation($"{defaultValue} => {result}");
  110. return result;
  111. }
  112. /// <summary>
  113. /// 处理错误信息
  114. /// </summary>
  115. /// <param name="context"></param>
  116. /// <param name="error"></param>
  117. /// <returns></returns>
  118. private static async Task HandleErrorAsync(HttpContext context, ForwarderError error)
  119. {
  120. if (error == ForwarderError.None || context.Response.HasStarted)
  121. {
  122. return;
  123. }
  124. await context.Response.WriteAsJsonAsync(new
  125. {
  126. error = error.ToString(),
  127. message = context.GetForwarderErrorFeature()?.Exception?.Message
  128. });
  129. }
  130. }
  131. }