process.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package xray
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io/fs"
  8. "os"
  9. "os/exec"
  10. "runtime"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "x-ui/config"
  15. "x-ui/logger"
  16. "x-ui/util/common"
  17. )
  18. func GetBinaryName() string {
  19. return fmt.Sprintf("xray-%s-%s", runtime.GOOS, runtime.GOARCH)
  20. }
  21. func GetBinaryPath() string {
  22. return config.GetBinFolderPath() + "/" + GetBinaryName()
  23. }
  24. func GetConfigPath() string {
  25. return config.GetBinFolderPath() + "/config.json"
  26. }
  27. func GetGeositePath() string {
  28. return config.GetBinFolderPath() + "/geosite.dat"
  29. }
  30. func GetGeoipPath() string {
  31. return config.GetBinFolderPath() + "/geoip.dat"
  32. }
  33. func GetIPLimitLogPath() string {
  34. return config.GetLogFolder() + "/3xipl.log"
  35. }
  36. func GetIPLimitBannedLogPath() string {
  37. return config.GetLogFolder() + "/3xipl-banned.log"
  38. }
  39. func GetIPLimitBannedPrevLogPath() string {
  40. return config.GetLogFolder() + "/3xipl-banned.prev.log"
  41. }
  42. func GetAccessPersistentLogPath() string {
  43. return config.GetLogFolder() + "/3xipl-ap.log"
  44. }
  45. func GetAccessPersistentPrevLogPath() string {
  46. return config.GetLogFolder() + "/3xipl-ap.prev.log"
  47. }
  48. func GetAccessLogPath() (string, error) {
  49. config, err := os.ReadFile(GetConfigPath())
  50. if err != nil {
  51. logger.Warningf("Failed to read configuration file: %s", err)
  52. return "", err
  53. }
  54. jsonConfig := map[string]any{}
  55. err = json.Unmarshal([]byte(config), &jsonConfig)
  56. if err != nil {
  57. logger.Warningf("Failed to parse JSON configuration: %s", err)
  58. return "", err
  59. }
  60. if jsonConfig["log"] != nil {
  61. jsonLog := jsonConfig["log"].(map[string]any)
  62. if jsonLog["access"] != nil {
  63. accessLogPath := jsonLog["access"].(string)
  64. return accessLogPath, nil
  65. }
  66. }
  67. return "", err
  68. }
  69. func stopProcess(p *Process) {
  70. p.Stop()
  71. }
  72. type Process struct {
  73. *process
  74. }
  75. func NewProcess(xrayConfig *Config) *Process {
  76. p := &Process{newProcess(xrayConfig)}
  77. runtime.SetFinalizer(p, stopProcess)
  78. return p
  79. }
  80. type process struct {
  81. cmd *exec.Cmd
  82. version string
  83. apiPort int
  84. onlineClients []string
  85. config *Config
  86. logWriter *LogWriter
  87. exitErr error
  88. startTime time.Time
  89. }
  90. func newProcess(config *Config) *process {
  91. return &process{
  92. version: "Unknown",
  93. config: config,
  94. logWriter: NewLogWriter(),
  95. startTime: time.Now(),
  96. }
  97. }
  98. func (p *process) IsRunning() bool {
  99. if p.cmd == nil || p.cmd.Process == nil {
  100. return false
  101. }
  102. if p.cmd.ProcessState == nil {
  103. return true
  104. }
  105. return false
  106. }
  107. func (p *process) GetErr() error {
  108. return p.exitErr
  109. }
  110. func (p *process) GetResult() string {
  111. if len(p.logWriter.lastLine) == 0 && p.exitErr != nil {
  112. return p.exitErr.Error()
  113. }
  114. return p.logWriter.lastLine
  115. }
  116. func (p *process) GetVersion() string {
  117. return p.version
  118. }
  119. func (p *Process) GetAPIPort() int {
  120. return p.apiPort
  121. }
  122. func (p *Process) GetConfig() *Config {
  123. return p.config
  124. }
  125. func (p *Process) GetOnlineClients() []string {
  126. return p.onlineClients
  127. }
  128. func (p *Process) SetOnlineClients(users []string) {
  129. p.onlineClients = users
  130. }
  131. func (p *Process) GetUptime() uint64 {
  132. return uint64(time.Since(p.startTime).Seconds())
  133. }
  134. func (p *process) refreshAPIPort() {
  135. for _, inbound := range p.config.InboundConfigs {
  136. if inbound.Tag == "api" {
  137. p.apiPort = inbound.Port
  138. break
  139. }
  140. }
  141. }
  142. func (p *process) refreshVersion() {
  143. cmd := exec.Command(GetBinaryPath(), "-version")
  144. data, err := cmd.Output()
  145. if err != nil {
  146. p.version = "Unknown"
  147. } else {
  148. datas := bytes.Split(data, []byte(" "))
  149. if len(datas) <= 1 {
  150. p.version = "Unknown"
  151. } else {
  152. p.version = string(datas[1])
  153. }
  154. }
  155. }
  156. func (p *process) Start() (err error) {
  157. if p.IsRunning() {
  158. return errors.New("xray is already running")
  159. }
  160. defer func() {
  161. if err != nil {
  162. logger.Error("Failure in running xray-core process: ", err)
  163. p.exitErr = err
  164. }
  165. }()
  166. data, err := json.MarshalIndent(p.config, "", " ")
  167. if err != nil {
  168. return common.NewErrorf("Failed to generate XRAY configuration files: %v", err)
  169. }
  170. err = os.MkdirAll(config.GetLogFolder(), 0o770)
  171. if err != nil {
  172. logger.Warningf("Failed to create log folder: %s", err)
  173. }
  174. configPath := GetConfigPath()
  175. err = os.WriteFile(configPath, data, fs.ModePerm)
  176. if err != nil {
  177. return common.NewErrorf("Failed to write configuration file: %v", err)
  178. }
  179. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  180. p.cmd = cmd
  181. cmd.Stdout = p.logWriter
  182. cmd.Stderr = p.logWriter
  183. go func() {
  184. err := cmd.Run()
  185. if err != nil {
  186. // On Windows, killing the process results in "exit status 1" which isn't an error for us
  187. if runtime.GOOS == "windows" {
  188. errStr := strings.ToLower(err.Error())
  189. if strings.Contains(errStr, "exit status 1") {
  190. // Suppress noisy log on graceful stop
  191. p.exitErr = err
  192. return
  193. }
  194. }
  195. logger.Error("Failure in running xray-core:", err)
  196. p.exitErr = err
  197. }
  198. }()
  199. p.refreshVersion()
  200. p.refreshAPIPort()
  201. return nil
  202. }
  203. func (p *process) Stop() error {
  204. if !p.IsRunning() {
  205. return errors.New("xray is not running")
  206. }
  207. if runtime.GOOS == "windows" {
  208. return p.cmd.Process.Kill()
  209. } else {
  210. return p.cmd.Process.Signal(syscall.SIGTERM)
  211. }
  212. }
  213. func writeCrashReport(m []byte) error {
  214. crashReportPath := config.GetBinFolderPath() + "/core_crash_" + time.Now().Format("20060102_150405") + ".log"
  215. return os.WriteFile(crashReportPath, m, os.ModePerm)
  216. }