CaCertInstallerOfLinux.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using FastGithub;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Runtime.InteropServices;
  8. namespace FastGithub.HttpServer.Certs.CaCertInstallers
  9. {
  10. abstract class CaCertInstallerOfLinux : ICaCertInstaller
  11. {
  12. private readonly ILogger logger;
  13. /// <summary>
  14. /// 更新工具文件名
  15. /// </summary>
  16. protected abstract string CaCertUpdatePath { get; }
  17. /// <summary>
  18. /// 证书根目录
  19. /// </summary>
  20. protected abstract string CaCertStorePath { get; }
  21. [DllImport("libc", SetLastError = true)]
  22. private static extern uint geteuid();
  23. public CaCertInstallerOfLinux(ILogger logger)
  24. {
  25. this.logger = logger;
  26. }
  27. /// <summary>
  28. /// 是否支持
  29. /// </summary>
  30. /// <returns></returns>
  31. public bool IsSupported()
  32. {
  33. return OperatingSystem.IsLinux() && File.Exists(CaCertUpdatePath);
  34. }
  35. /// <summary>
  36. /// 安装ca证书
  37. /// </summary>
  38. /// <param name="caCertFilePath">证书文件路径</param>
  39. public void Install(string caCertFilePath)
  40. {
  41. var destCertFilePath = Path.Combine(CaCertStorePath, Path.GetFileName(caCertFilePath));
  42. if (File.Exists(destCertFilePath) && File.ReadAllBytes(caCertFilePath).SequenceEqual(File.ReadAllBytes(destCertFilePath)))
  43. {
  44. return;
  45. }
  46. if (geteuid() != 0)
  47. {
  48. logger.LogWarning($"无法自动安装CA证书{caCertFilePath}:没有root权限");
  49. return;
  50. }
  51. try
  52. {
  53. Directory.CreateDirectory(CaCertStorePath);
  54. foreach (var item in Directory.GetFiles(CaCertStorePath, "fastgithub.*"))
  55. {
  56. File.Delete(item);
  57. }
  58. File.Copy(caCertFilePath, destCertFilePath, overwrite: true);
  59. Process.Start(CaCertUpdatePath).WaitForExit();
  60. logger.LogInformation($"已自动向系统安装CA证书{caCertFilePath}");
  61. }
  62. catch (Exception ex)
  63. {
  64. File.Delete(destCertFilePath);
  65. logger.LogWarning(ex.Message, "自动安装CA证书异常");
  66. }
  67. }
  68. }
  69. }