HttpProxyMiddleware.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. using FastGithub.Configuration;
  2. using FastGithub.DomainResolve;
  3. using Microsoft.AspNetCore.Connections.Features;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.AspNetCore.Http.Features;
  6. using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.IO.Pipelines;
  11. using System.Net;
  12. using System.Net.Http;
  13. using System.Net.Sockets;
  14. using System.Reflection;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using Yarp.ReverseProxy.Forwarder;
  19. namespace FastGithub.HttpServer
  20. {
  21. /// <summary>
  22. /// http代理中间件
  23. /// </summary>
  24. sealed class HttpProxyMiddleware
  25. {
  26. private const string LOCALHOST = "localhost";
  27. private const int HTTP_PORT = 80;
  28. private const int HTTPS_PORT = 443;
  29. private readonly FastGithubConfig fastGithubConfig;
  30. private readonly IDomainResolver domainResolver;
  31. private readonly IHttpForwarder httpForwarder;
  32. private readonly HttpReverseProxyMiddleware httpReverseProxy;
  33. private readonly HttpMessageInvoker defaultHttpClient;
  34. private readonly TimeSpan connectTimeout = TimeSpan.FromSeconds(10d);
  35. static HttpProxyMiddleware()
  36. {
  37. // https://github.com/dotnet/aspnetcore/issues/37421
  38. var authority = typeof(HttpParser<>).Assembly
  39. .GetType("Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure.HttpCharacters")?
  40. .GetField("_authority", BindingFlags.NonPublic | BindingFlags.Static)?
  41. .GetValue(null);
  42. if (authority is bool[] authorityArray)
  43. {
  44. authorityArray['-'] = true;
  45. }
  46. }
  47. /// <summary>
  48. /// http代理中间件
  49. /// </summary>
  50. /// <param name="fastGithubConfig"></param>
  51. /// <param name="domainResolver"></param>
  52. /// <param name="httpForwarder"></param>
  53. /// <param name="httpReverseProxy"></param>
  54. public HttpProxyMiddleware(
  55. FastGithubConfig fastGithubConfig,
  56. IDomainResolver domainResolver,
  57. IHttpForwarder httpForwarder,
  58. HttpReverseProxyMiddleware httpReverseProxy)
  59. {
  60. this.fastGithubConfig = fastGithubConfig;
  61. this.domainResolver = domainResolver;
  62. this.httpForwarder = httpForwarder;
  63. this.httpReverseProxy = httpReverseProxy;
  64. this.defaultHttpClient = new HttpMessageInvoker(CreateDefaultHttpHandler(), disposeHandler: false);
  65. }
  66. /// <summary>
  67. /// 处理请求
  68. /// </summary>
  69. /// <param name="context"></param>
  70. /// <returns></returns>
  71. public async Task InvokeAsync(HttpContext context)
  72. {
  73. var host = context.Request.Host;
  74. if (this.IsFastGithubServer(host) == true)
  75. {
  76. var proxyPac = this.CreateProxyPac(host);
  77. context.Response.ContentType = "application/x-ns-proxy-autoconfig";
  78. context.Response.Headers.Add("Content-Disposition", $"attachment;filename=proxy.pac");
  79. await context.Response.WriteAsync(proxyPac);
  80. }
  81. else if (context.Request.Method == HttpMethods.Connect)
  82. {
  83. using var connection = await this.CreateConnectionAsync(host);
  84. var responseFeature = context.Features.Get<IHttpResponseFeature>();
  85. if (responseFeature != null)
  86. {
  87. responseFeature.ReasonPhrase = "Connection Established";
  88. }
  89. context.Response.StatusCode = StatusCodes.Status200OK;
  90. await context.Response.CompleteAsync();
  91. var transport = context.Features.Get<IConnectionTransportFeature>()?.Transport;
  92. if (transport != null)
  93. {
  94. await Task.WhenAny(connection.CopyToAsync(transport.Output), transport.Input.CopyToAsync(connection));
  95. }
  96. }
  97. else
  98. {
  99. await this.httpReverseProxy.InvokeAsync(context, async next =>
  100. {
  101. var destinationPrefix = $"{context.Request.Scheme}://{context.Request.Host}";
  102. await this.httpForwarder.SendAsync(context, destinationPrefix, this.defaultHttpClient);
  103. });
  104. }
  105. }
  106. /// <summary>
  107. /// 是否为fastgithub服务
  108. /// </summary>
  109. /// <param name="host"></param>
  110. /// <returns></returns>
  111. private bool IsFastGithubServer(HostString host)
  112. {
  113. if (host.Port != this.fastGithubConfig.HttpProxyPort)
  114. {
  115. return false;
  116. }
  117. if (host.Host == LOCALHOST)
  118. {
  119. return true;
  120. }
  121. return IPAddress.TryParse(host.Host, out var address) && IPAddress.IsLoopback(address);
  122. }
  123. /// <summary>
  124. /// 创建proxypac脚本
  125. /// </summary>
  126. /// <param name="proxyHost"></param>
  127. /// <returns></returns>
  128. private string CreateProxyPac(HostString proxyHost)
  129. {
  130. var buidler = new StringBuilder();
  131. buidler.AppendLine("function FindProxyForURL(url, host){");
  132. buidler.AppendLine($" var fastgithub = 'PROXY {proxyHost}';");
  133. foreach (var domain in this.fastGithubConfig.GetDomainPatterns())
  134. {
  135. buidler.AppendLine($" if (shExpMatch(host, '{domain}')) return fastgithub;");
  136. }
  137. buidler.AppendLine(" return 'DIRECT';");
  138. buidler.AppendLine("}");
  139. return buidler.ToString();
  140. }
  141. /// <summary>
  142. /// 创建连接
  143. /// </summary>
  144. /// <param name="host"></param>
  145. /// <returns></returns>
  146. /// <exception cref="AggregateException"></exception>
  147. private async Task<Stream> CreateConnectionAsync(HostString host)
  148. {
  149. var innerExceptions = new List<Exception>();
  150. await foreach (var endPoint in this.GetTargetEndPointsAsync(host))
  151. {
  152. var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  153. try
  154. {
  155. using var timeoutTokenSource = new CancellationTokenSource(this.connectTimeout);
  156. await socket.ConnectAsync(endPoint, timeoutTokenSource.Token);
  157. return new NetworkStream(socket, ownsSocket: false);
  158. }
  159. catch (Exception ex)
  160. {
  161. socket.Dispose();
  162. innerExceptions.Add(ex);
  163. }
  164. }
  165. throw new AggregateException($"无法连接到{host}", innerExceptions);
  166. }
  167. /// <summary>
  168. /// 获取目标终节点
  169. /// </summary>
  170. /// <param name="host"></param>
  171. /// <returns></returns>
  172. private async IAsyncEnumerable<EndPoint> GetTargetEndPointsAsync(HostString host)
  173. {
  174. var targetHost = host.Host;
  175. var targetPort = host.Port ?? HTTPS_PORT;
  176. if (IPAddress.TryParse(targetHost, out var address) == true)
  177. {
  178. yield return new IPEndPoint(address, targetPort);
  179. yield break;
  180. }
  181. // 不关心的域名,直接使用系统dns
  182. if (this.fastGithubConfig.IsMatch(targetHost) == false)
  183. {
  184. yield return new DnsEndPoint(targetHost, targetPort);
  185. yield break;
  186. }
  187. if (targetPort == HTTP_PORT)
  188. {
  189. yield return new IPEndPoint(IPAddress.Loopback, ReverseProxyPort.Http);
  190. yield break;
  191. }
  192. if (targetPort == HTTPS_PORT)
  193. {
  194. yield return new IPEndPoint(IPAddress.Loopback, ReverseProxyPort.Https);
  195. yield break;
  196. }
  197. var dnsEndPoint = new DnsEndPoint(targetHost, targetPort);
  198. await foreach (var item in this.domainResolver.ResolveAsync(dnsEndPoint))
  199. {
  200. yield return new IPEndPoint(item, targetPort);
  201. }
  202. }
  203. /// <summary>
  204. /// 创建httpHandler
  205. /// </summary>
  206. /// <returns></returns>
  207. private static SocketsHttpHandler CreateDefaultHttpHandler()
  208. {
  209. return new()
  210. {
  211. Proxy = null,
  212. UseProxy = false,
  213. UseCookies = false,
  214. AllowAutoRedirect = false,
  215. AutomaticDecompression = DecompressionMethods.None
  216. };
  217. }
  218. }
  219. }