CaCertInstallerOfLinux.cs 2.2 KB

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