run.go 4.4 KB

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