platform.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. ConfigLocation = "xray.location.config"
  10. ConfdirLocation = "xray.location.confdir"
  11. AssetLocation = "xray.location.asset"
  12. CertLocation = "xray.location.cert"
  13. UseReadV = "xray.buf.readv"
  14. UseFreedomSplice = "xray.buf.splice"
  15. UseVmessPadding = "xray.vmess.padding"
  16. UseCone = "xray.cone.disabled"
  17. BufferSize = "xray.ray.buffer.size"
  18. BrowserDialerAddress = "xray.browser.dialer"
  19. XUDPLog = "xray.xudp.show"
  20. XUDPBaseKey = "xray.xudp.basekey"
  21. TunFdKey = "xray.tun.fd"
  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 GetConfigurationPath() string {
  70. configPath := NewEnvFlag(ConfigLocation).GetValue(getExecutableDir)
  71. return filepath.Join(configPath, "config.json")
  72. }
  73. // GetConfDirPath reads "xray.location.confdir"
  74. func GetConfDirPath() string {
  75. configPath := NewEnvFlag(ConfdirLocation).GetValue(func() string { return "" })
  76. return configPath
  77. }