platform.go 2.2 KB

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