run.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "os/signal"
  7. "path"
  8. "path/filepath"
  9. "regexp"
  10. "runtime"
  11. "runtime/debug"
  12. "strings"
  13. "syscall"
  14. "github.com/xtls/xray-core/common/cmdarg"
  15. "github.com/xtls/xray-core/common/platform"
  16. "github.com/xtls/xray-core/core"
  17. "github.com/xtls/xray-core/main/commands/base"
  18. )
  19. var cmdRun = &base.Command{
  20. UsageLine: "{{.Exec}} run [-c config.json] [-confdir dir]",
  21. Short: "Run Xray with config, the default command",
  22. Long: `
  23. Run Xray with config, the default command.
  24. The -config=file, -c=file flags set the config files for
  25. Xray. Multiple assign is accepted.
  26. The -confdir=dir flag sets a dir with multiple json config
  27. The -format=json flag sets the format of config files.
  28. Default "auto".
  29. The -test flag tells Xray to test config files only,
  30. without launching the server
  31. `,
  32. }
  33. func init() {
  34. cmdRun.Run = executeRun // break init loop
  35. }
  36. var (
  37. configFiles cmdarg.Arg // "Config file for Xray.", the option is customed type, parse in main
  38. configDir string
  39. test = cmdRun.Flag.Bool("test", false, "Test config file only, without launching Xray server.")
  40. format = cmdRun.Flag.String("format", "auto", "Format of input file.")
  41. /* We have to do this here because Golang's Test will also need to parse flag, before
  42. * main func in this file is run.
  43. */
  44. _ = func() bool {
  45. cmdRun.Flag.Var(&configFiles, "config", "Config path for Xray.")
  46. cmdRun.Flag.Var(&configFiles, "c", "Short alias of -config")
  47. cmdRun.Flag.StringVar(&configDir, "confdir", "", "A dir with multiple json config")
  48. return true
  49. }()
  50. )
  51. func executeRun(cmd *base.Command, args []string) {
  52. printVersion()
  53. server, err := startXray()
  54. if err != nil {
  55. fmt.Println("Failed to start:", err)
  56. // Configuration error. Exit with a special value to prevent systemd from restarting.
  57. os.Exit(23)
  58. }
  59. if *test {
  60. fmt.Println("Configuration OK.")
  61. os.Exit(0)
  62. }
  63. if err := server.Start(); err != nil {
  64. fmt.Println("Failed to start:", err)
  65. os.Exit(-1)
  66. }
  67. defer server.Close()
  68. /*
  69. conf.FileCache = nil
  70. conf.IPCache = nil
  71. conf.SiteCache = nil
  72. */
  73. // Explicitly triggering GC to remove garbage from config loading.
  74. runtime.GC()
  75. debug.FreeOSMemory()
  76. {
  77. osSignals := make(chan os.Signal, 1)
  78. signal.Notify(osSignals, os.Interrupt, syscall.SIGTERM)
  79. <-osSignals
  80. }
  81. }
  82. func fileExists(file string) bool {
  83. info, err := os.Stat(file)
  84. return err == nil && !info.IsDir()
  85. }
  86. func dirExists(file string) bool {
  87. if file == "" {
  88. return false
  89. }
  90. info, err := os.Stat(file)
  91. return err == nil && info.IsDir()
  92. }
  93. func getRegepxByFormat() string {
  94. switch strings.ToLower(*format) {
  95. case "json":
  96. return `^.+\.json$`
  97. case "toml":
  98. return `^.+\.toml$`
  99. case "yaml", "yml":
  100. return `^.+\.(yaml|yml)$`
  101. default:
  102. return `^.+\.(json|toml|yaml|yml)$`
  103. }
  104. }
  105. func readConfDir(dirPath string) {
  106. confs, err := os.ReadDir(dirPath)
  107. if err != nil {
  108. log.Fatalln(err)
  109. }
  110. for _, f := range confs {
  111. matched, err := regexp.MatchString(getRegepxByFormat(), f.Name())
  112. if err != nil {
  113. log.Fatalln(err)
  114. }
  115. if matched {
  116. configFiles.Set(path.Join(dirPath, f.Name()))
  117. }
  118. }
  119. }
  120. func getConfigFilePath() cmdarg.Arg {
  121. if dirExists(configDir) {
  122. log.Println("Using confdir from arg:", configDir)
  123. readConfDir(configDir)
  124. } else if envConfDir := platform.GetConfDirPath(); dirExists(envConfDir) {
  125. log.Println("Using confdir from env:", envConfDir)
  126. readConfDir(envConfDir)
  127. }
  128. if len(configFiles) > 0 {
  129. return configFiles
  130. }
  131. if workingDir, err := os.Getwd(); err == nil {
  132. configFile := filepath.Join(workingDir, "config.json")
  133. if fileExists(configFile) {
  134. log.Println("Using default config: ", configFile)
  135. return cmdarg.Arg{configFile}
  136. }
  137. }
  138. if configFile := platform.GetConfigurationPath(); fileExists(configFile) {
  139. log.Println("Using config from env: ", configFile)
  140. return cmdarg.Arg{configFile}
  141. }
  142. log.Println("Using config from STDIN")
  143. return cmdarg.Arg{"stdin:"}
  144. }
  145. func getConfigFormat() string {
  146. f := core.GetFormatByExtension(*format)
  147. if f == "" {
  148. f = "auto"
  149. }
  150. return f
  151. }
  152. func startXray() (core.Server, error) {
  153. configFiles := getConfigFilePath()
  154. // config, err := core.LoadConfig(getConfigFormat(), configFiles[0], configFiles)
  155. c, err := core.LoadConfig(getConfigFormat(), configFiles)
  156. if err != nil {
  157. return nil, newError("failed to load config files: [", configFiles.String(), "]").Base(err)
  158. }
  159. server, err := core.New(c)
  160. if err != nil {
  161. return nil, newError("failed to create server").Base(err)
  162. }
  163. return server, nil
  164. }