TunnelMiddleware.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. using FastGithub.Configuration;
  2. using FastGithub.DomainResolve;
  3. using Microsoft.AspNetCore.Connections;
  4. using Microsoft.AspNetCore.Connections.Features;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.AspNetCore.Http.Features;
  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.Sockets;
  13. using System.Runtime.CompilerServices;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace FastGithub.HttpServer.TcpMiddlewares
  17. {
  18. /// <summary>
  19. /// 隧道中间件
  20. /// </summary>
  21. sealed class TunnelMiddleware
  22. {
  23. private readonly FastGithubConfig fastGithubConfig;
  24. private readonly IDomainResolver domainResolver;
  25. private readonly TimeSpan connectTimeout = TimeSpan.FromSeconds(10d);
  26. /// <summary>
  27. /// 隧道中间件
  28. /// </summary>
  29. /// <param name="fastGithubConfig"></param>
  30. /// <param name="domainResolver"></param>
  31. public TunnelMiddleware(
  32. FastGithubConfig fastGithubConfig,
  33. IDomainResolver domainResolver)
  34. {
  35. this.fastGithubConfig = fastGithubConfig;
  36. this.domainResolver = domainResolver;
  37. }
  38. /// <summary>
  39. /// 执行中间件
  40. /// </summary>
  41. /// <param name="next"></param>
  42. /// <param name="context"></param>
  43. /// <returns></returns>
  44. public async Task InvokeAsync(ConnectionDelegate next, ConnectionContext context)
  45. {
  46. var proxyFeature = context.Features.Get<IHttpProxyFeature>();
  47. if (proxyFeature == null || // 非代理
  48. proxyFeature.ProxyProtocol != ProxyProtocol.TunnelProxy || //非隧道代理
  49. context.Features.Get<ITlsConnectionFeature>() != null) // 经过隧道的https
  50. {
  51. await next(context);
  52. }
  53. else
  54. {
  55. var transport = context.Features.Get<IConnectionTransportFeature>()?.Transport;
  56. if (transport != null)
  57. {
  58. var cancellationToken = context.ConnectionClosed;
  59. using var connection = await this.CreateConnectionAsync(proxyFeature.ProxyHost, cancellationToken);
  60. var task1 = connection.CopyToAsync(transport.Output, cancellationToken);
  61. var task2 = transport.Input.CopyToAsync(connection, cancellationToken);
  62. await Task.WhenAny(task1, task2);
  63. }
  64. }
  65. }
  66. /// <summary>
  67. /// 创建连接
  68. /// </summary>
  69. /// <param name="host"></param>
  70. /// <param name="cancellationToken"></param>
  71. /// <returns></returns>
  72. /// <exception cref="AggregateException"></exception>
  73. private async Task<Stream> CreateConnectionAsync(HostString host, CancellationToken cancellationToken)
  74. {
  75. var innerExceptions = new List<Exception>();
  76. await foreach (var endPoint in this.GetUpstreamEndPointsAsync(host, cancellationToken))
  77. {
  78. var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
  79. try
  80. {
  81. using var timeoutTokenSource = new CancellationTokenSource(this.connectTimeout);
  82. using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutTokenSource.Token);
  83. await socket.ConnectAsync(endPoint, linkedTokenSource.Token);
  84. return new NetworkStream(socket, ownsSocket: true);
  85. }
  86. catch (Exception ex)
  87. {
  88. socket.Dispose();
  89. cancellationToken.ThrowIfCancellationRequested();
  90. innerExceptions.Add(ex);
  91. }
  92. }
  93. throw new AggregateException($"无法连接到{host}", innerExceptions);
  94. }
  95. /// <summary>
  96. /// 获取目标终节点
  97. /// </summary>
  98. /// <param name="host"></param>
  99. /// <param name="cancellationToken"></param>
  100. /// <returns></returns>
  101. private async IAsyncEnumerable<EndPoint> GetUpstreamEndPointsAsync(HostString host, [EnumeratorCancellation] CancellationToken cancellationToken)
  102. {
  103. const int HTTPS_PORT = 443;
  104. var targetHost = host.Host;
  105. var targetPort = host.Port ?? HTTPS_PORT;
  106. if (IPAddress.TryParse(targetHost, out var address) == true)
  107. {
  108. yield return new IPEndPoint(address, targetPort);
  109. }
  110. else if (this.fastGithubConfig.IsMatch(targetHost) == false)
  111. {
  112. yield return new DnsEndPoint(targetHost, targetPort);
  113. }
  114. else
  115. {
  116. var dnsEndPoint = new DnsEndPoint(targetHost, targetPort);
  117. await foreach (var item in this.domainResolver.ResolveAsync(dnsEndPoint, cancellationToken))
  118. {
  119. yield return new IPEndPoint(item, targetPort);
  120. }
  121. }
  122. }
  123. }
  124. }