platform.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package platform // import "github.com/xtls/xray-core/common/platform"
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strconv"
  6. "strings"
  7. )
  8. const (
  9. PluginLocation = "xray.location.plugin"
  10. ConfigLocation = "xray.location.config"
  11. ConfdirLocation = "xray.location.confdir"
  12. ToolLocation = "xray.location.tool"
  13. AssetLocation = "xray.location.asset"
  14. CertLocation = "xray.location.cert"
  15. UseReadV = "xray.buf.readv"
  16. UseFreedomSplice = "xray.buf.splice"
  17. UseVmessPadding = "xray.vmess.padding"
  18. UseCone = "xray.cone.disabled"
  19. BufferSize = "xray.ray.buffer.size"
  20. BrowserDialerAddress = "xray.browser.dialer"
  21. XUDPLog = "xray.xudp.show"
  22. XUDPBaseKey = "xray.xudp.basekey"
  23. )
  24. type EnvFlag struct {
  25. Name string
  26. AltName string
  27. }
  28. func NewEnvFlag(name string) EnvFlag {
  29. return EnvFlag{
  30. Name: name,
  31. AltName: NormalizeEnvName(name),
  32. }
  33. }
  34. func (f EnvFlag) GetValue(defaultValue func() string) string {
  35. if v, found := os.LookupEnv(f.Name); found {
  36. return v
  37. }
  38. if len(f.AltName) > 0 {
  39. if v, found := os.LookupEnv(f.AltName); found {
  40. return v
  41. }
  42. }
  43. return defaultValue()
  44. }
  45. func (f EnvFlag) GetValueAsInt(defaultValue int) int {
  46. useDefaultValue := false
  47. s := f.GetValue(func() string {
  48. useDefaultValue = true
  49. return ""
  50. })
  51. if useDefaultValue {
  52. return defaultValue
  53. }
  54. v, err := strconv.ParseInt(s, 10, 32)
  55. if err != nil {
  56. return defaultValue
  57. }
  58. return int(v)
  59. }
  60. func NormalizeEnvName(name string) string {
  61. return strings.ReplaceAll(strings.ToUpper(strings.TrimSpace(name)), ".", "_")
  62. }
  63. func getExecutableDir() string {
  64. exec, err := os.Executable()
  65. if err != nil {
  66. return ""
  67. }
  68. return filepath.Dir(exec)
  69. }
  70. func getExecutableSubDir(dir string) func() string {
  71. return func() string {
  72. return filepath.Join(getExecutableDir(), dir)
  73. }
  74. }
  75. func GetPluginDirectory() string {
  76. pluginDir := NewEnvFlag(PluginLocation).GetValue(getExecutableSubDir("plugins"))
  77. return pluginDir
  78. }
  79. func GetConfigurationPath() string {
  80. configPath := NewEnvFlag(ConfigLocation).GetValue(getExecutableDir)
  81. return filepath.Join(configPath, "config.json")
  82. }
  83. // GetConfDirPath reads "xray.location.confdir"
  84. func GetConfDirPath() string {
  85. configPath := NewEnvFlag(ConfdirLocation).GetValue(func() string { return "" })
  86. return configPath
  87. }