HttpProxyMiddleware.cs 9.2 KB

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