run.go 5.1 KB

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