KestrelServerOptionsExtensions.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using FastGithub.Configuration;
  2. using FastGithub.ReverseProxy;
  3. using Microsoft.AspNetCore.Hosting;
  4. using Microsoft.AspNetCore.Server.Kestrel.Core;
  5. using Microsoft.Extensions.DependencyInjection;
  6. using Microsoft.Extensions.Logging;
  7. using System;
  8. using System.Net;
  9. using System.Security.Authentication;
  10. namespace FastGithub
  11. {
  12. /// <summary>
  13. /// Kestrel扩展
  14. /// </summary>
  15. public static class KestrelServerOptionsExtensions
  16. {
  17. /// <summary>
  18. /// 监听http的反向代理
  19. /// </summary>
  20. /// <param name="kestrel"></param>
  21. public static void ListenHttpReverseProxy(this KestrelServerOptions kestrel)
  22. {
  23. const int HTTP_PORT = 80;
  24. if (OperatingSystem.IsWindows())
  25. {
  26. TcpTable.KillPortOwner(HTTP_PORT);
  27. }
  28. if (LocalMachine.CanListenTcp(HTTP_PORT) == false)
  29. {
  30. var loggerFactory = kestrel.ApplicationServices.GetRequiredService<ILoggerFactory>();
  31. var logger = loggerFactory.CreateLogger($"{nameof(FastGithub)}.{nameof(ReverseProxy)}");
  32. logger.LogWarning($"由于tcp端口{HTTP_PORT}已经被其它进程占用,http反向代理功能将受限");
  33. }
  34. else
  35. {
  36. kestrel.Listen(IPAddress.Any, HTTP_PORT);
  37. }
  38. }
  39. /// <summary>
  40. /// 监听https的反向代理
  41. /// </summary>
  42. /// <param name="kestrel"></param>
  43. public static void ListenHttpsReverseProxy(this KestrelServerOptions kestrel)
  44. {
  45. const int HTTPS_PORT = 443;
  46. if (OperatingSystem.IsWindows())
  47. {
  48. TcpTable.KillPortOwner(HTTPS_PORT);
  49. }
  50. if (LocalMachine.CanListenTcp(HTTPS_PORT) == false)
  51. {
  52. throw new FastGithubException($"由于tcp端口{HTTPS_PORT}已经被其它进程占用,{nameof(FastGithub)}无法进行必须的https反向代理");
  53. }
  54. var certService = kestrel.ApplicationServices.GetRequiredService<CertService>();
  55. certService.CreateCaCertIfNotExists();
  56. certService.InstallAndTrustCaCert();
  57. kestrel.Listen(IPAddress.Any, HTTPS_PORT, listen => listen.UseHttps(https =>
  58. {
  59. if (OperatingSystem.IsWindows() && Environment.OSVersion.Version < new Version(6, 2))
  60. {
  61. https.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13;
  62. }
  63. https.ServerCertificateSelector = (ctx, domain) => certService.GetOrCreateServerCert(domain);
  64. }));
  65. }
  66. }
  67. }