platform.go 2.1 KB

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