platform.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. )
  22. type EnvFlag struct {
  23. Name string
  24. AltName string
  25. }
  26. func NewEnvFlag(name string) EnvFlag {
  27. return EnvFlag{
  28. Name: name,
  29. AltName: NormalizeEnvName(name),
  30. }
  31. }
  32. func (f EnvFlag) GetValue(defaultValue func() string) string {
  33. if v, found := os.LookupEnv(f.Name); found {
  34. return v
  35. }
  36. if len(f.AltName) > 0 {
  37. if v, found := os.LookupEnv(f.AltName); found {
  38. return v
  39. }
  40. }
  41. return defaultValue()
  42. }
  43. func (f EnvFlag) GetValueAsInt(defaultValue int) int {
  44. useDefaultValue := false
  45. s := f.GetValue(func() string {
  46. useDefaultValue = true
  47. return ""
  48. })
  49. if useDefaultValue {
  50. return defaultValue
  51. }
  52. v, err := strconv.ParseInt(s, 10, 32)
  53. if err != nil {
  54. return defaultValue
  55. }
  56. return int(v)
  57. }
  58. func NormalizeEnvName(name string) string {
  59. return strings.ReplaceAll(strings.ToUpper(strings.TrimSpace(name)), ".", "_")
  60. }
  61. func getExecutableDir() string {
  62. exec, err := os.Executable()
  63. if err != nil {
  64. return ""
  65. }
  66. return filepath.Dir(exec)
  67. }
  68. func GetConfigurationPath() string {
  69. configPath := NewEnvFlag(ConfigLocation).GetValue(getExecutableDir)
  70. return filepath.Join(configPath, "config.json")
  71. }
  72. // GetConfDirPath reads "xray.location.confdir"
  73. func GetConfDirPath() string {
  74. configPath := NewEnvFlag(ConfdirLocation).GetValue(func() string { return "" })
  75. return configPath
  76. }