run.go 5.2 KB

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