CaCertInstallerOfLinux.cs 2.1 KB

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