process.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. "github.com/mhsanaei/3x-ui/v2/config"
  15. "github.com/mhsanaei/3x-ui/v2/logger"
  16. "github.com/mhsanaei/3x-ui/v2/util/common"
  17. )
  18. // GetBinaryName returns the Xray binary filename for the current OS and architecture.
  19. func GetBinaryName() string {
  20. return fmt.Sprintf("xray-%s-%s", runtime.GOOS, runtime.GOARCH)
  21. }
  22. // GetBinaryPath returns the full path to the Xray binary executable.
  23. func GetBinaryPath() string {
  24. return config.GetBinFolderPath() + "/" + GetBinaryName()
  25. }
  26. // GetConfigPath returns the path to the Xray configuration file in the binary folder.
  27. func GetConfigPath() string {
  28. return config.GetBinFolderPath() + "/config.json"
  29. }
  30. // GetGeositePath returns the path to the geosite data file used by Xray.
  31. func GetGeositePath() string {
  32. return config.GetBinFolderPath() + "/geosite.dat"
  33. }
  34. // GetGeoipPath returns the path to the geoip data file used by Xray.
  35. func GetGeoipPath() string {
  36. return config.GetBinFolderPath() + "/geoip.dat"
  37. }
  38. // GetIPLimitLogPath returns the path to the IP limit log file.
  39. func GetIPLimitLogPath() string {
  40. return config.GetLogFolder() + "/3xipl.log"
  41. }
  42. // GetIPLimitBannedLogPath returns the path to the banned IP log file.
  43. func GetIPLimitBannedLogPath() string {
  44. return config.GetLogFolder() + "/3xipl-banned.log"
  45. }
  46. // GetIPLimitBannedPrevLogPath returns the path to the previous banned IP log file.
  47. func GetIPLimitBannedPrevLogPath() string {
  48. return config.GetLogFolder() + "/3xipl-banned.prev.log"
  49. }
  50. // GetAccessPersistentLogPath returns the path to the persistent access log file.
  51. func GetAccessPersistentLogPath() string {
  52. return config.GetLogFolder() + "/3xipl-ap.log"
  53. }
  54. // GetAccessPersistentPrevLogPath returns the path to the previous persistent access log file.
  55. func GetAccessPersistentPrevLogPath() string {
  56. return config.GetLogFolder() + "/3xipl-ap.prev.log"
  57. }
  58. // GetAccessLogPath reads the Xray config and returns the access log file path.
  59. func GetAccessLogPath() (string, error) {
  60. config, err := os.ReadFile(GetConfigPath())
  61. if err != nil {
  62. logger.Warningf("Failed to read configuration file: %s", err)
  63. return "", err
  64. }
  65. jsonConfig := map[string]any{}
  66. err = json.Unmarshal([]byte(config), &jsonConfig)
  67. if err != nil {
  68. logger.Warningf("Failed to parse JSON configuration: %s", err)
  69. return "", err
  70. }
  71. if jsonConfig["log"] != nil {
  72. jsonLog := jsonConfig["log"].(map[string]any)
  73. if jsonLog["access"] != nil {
  74. accessLogPath := jsonLog["access"].(string)
  75. return accessLogPath, nil
  76. }
  77. }
  78. return "", err
  79. }
  80. // stopProcess calls Stop on the given Process instance.
  81. func stopProcess(p *Process) {
  82. p.Stop()
  83. }
  84. // Process wraps an Xray process instance and provides management methods.
  85. type Process struct {
  86. *process
  87. }
  88. // NewProcess creates a new Xray process and sets up cleanup on garbage collection.
  89. func NewProcess(xrayConfig *Config) *Process {
  90. p := &Process{newProcess(xrayConfig)}
  91. runtime.SetFinalizer(p, stopProcess)
  92. return p
  93. }
  94. type process struct {
  95. cmd *exec.Cmd
  96. version string
  97. apiPort int
  98. onlineClients []string
  99. config *Config
  100. logWriter *LogWriter
  101. exitErr error
  102. startTime time.Time
  103. }
  104. // newProcess creates a new internal process struct for Xray.
  105. func newProcess(config *Config) *process {
  106. return &process{
  107. version: "Unknown",
  108. config: config,
  109. logWriter: NewLogWriter(),
  110. startTime: time.Now(),
  111. }
  112. }
  113. // IsRunning returns true if the Xray process is currently running.
  114. func (p *process) IsRunning() bool {
  115. if p.cmd == nil || p.cmd.Process == nil {
  116. return false
  117. }
  118. if p.cmd.ProcessState == nil {
  119. return true
  120. }
  121. return false
  122. }
  123. // GetErr returns the last error encountered by the Xray process.
  124. func (p *process) GetErr() error {
  125. return p.exitErr
  126. }
  127. // GetResult returns the last log line or error from the Xray process.
  128. func (p *process) GetResult() string {
  129. if len(p.logWriter.lastLine) == 0 && p.exitErr != nil {
  130. return p.exitErr.Error()
  131. }
  132. return p.logWriter.lastLine
  133. }
  134. // GetVersion returns the version string of the Xray process.
  135. func (p *process) GetVersion() string {
  136. return p.version
  137. }
  138. // GetAPIPort returns the API port used by the Xray process.
  139. func (p *Process) GetAPIPort() int {
  140. return p.apiPort
  141. }
  142. // GetConfig returns the configuration used by the Xray process.
  143. func (p *Process) GetConfig() *Config {
  144. return p.config
  145. }
  146. // GetOnlineClients returns the list of online clients for the Xray process.
  147. func (p *Process) GetOnlineClients() []string {
  148. return p.onlineClients
  149. }
  150. // SetOnlineClients sets the list of online clients for the Xray process.
  151. func (p *Process) SetOnlineClients(users []string) {
  152. p.onlineClients = users
  153. }
  154. // GetUptime returns the uptime of the Xray process in seconds.
  155. func (p *Process) GetUptime() uint64 {
  156. return uint64(time.Since(p.startTime).Seconds())
  157. }
  158. // refreshAPIPort updates the API port from the inbound configs.
  159. func (p *process) refreshAPIPort() {
  160. for _, inbound := range p.config.InboundConfigs {
  161. if inbound.Tag == "api" {
  162. p.apiPort = inbound.Port
  163. break
  164. }
  165. }
  166. }
  167. // refreshVersion updates the version string by running the Xray binary with -version.
  168. func (p *process) refreshVersion() {
  169. cmd := exec.Command(GetBinaryPath(), "-version")
  170. data, err := cmd.Output()
  171. if err != nil {
  172. p.version = "Unknown"
  173. } else {
  174. datas := bytes.Split(data, []byte(" "))
  175. if len(datas) <= 1 {
  176. p.version = "Unknown"
  177. } else {
  178. p.version = string(datas[1])
  179. }
  180. }
  181. }
  182. // Start launches the Xray process with the current configuration.
  183. func (p *process) Start() (err error) {
  184. if p.IsRunning() {
  185. return errors.New("xray is already running")
  186. }
  187. defer func() {
  188. if err != nil {
  189. logger.Error("Failure in running xray-core process: ", err)
  190. p.exitErr = err
  191. }
  192. }()
  193. data, err := json.MarshalIndent(p.config, "", " ")
  194. if err != nil {
  195. return common.NewErrorf("Failed to generate XRAY configuration files: %v", err)
  196. }
  197. err = os.MkdirAll(config.GetLogFolder(), 0o770)
  198. if err != nil {
  199. logger.Warningf("Failed to create log folder: %s", err)
  200. }
  201. configPath := GetConfigPath()
  202. err = os.WriteFile(configPath, data, fs.ModePerm)
  203. if err != nil {
  204. return common.NewErrorf("Failed to write configuration file: %v", err)
  205. }
  206. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  207. p.cmd = cmd
  208. cmd.Stdout = p.logWriter
  209. cmd.Stderr = p.logWriter
  210. go func() {
  211. err := cmd.Run()
  212. if err != nil {
  213. // On Windows, killing the process results in "exit status 1" which isn't an error for us
  214. if runtime.GOOS == "windows" {
  215. errStr := strings.ToLower(err.Error())
  216. if strings.Contains(errStr, "exit status 1") {
  217. // Suppress noisy log on graceful stop
  218. p.exitErr = err
  219. return
  220. }
  221. }
  222. logger.Error("Failure in running xray-core:", err)
  223. p.exitErr = err
  224. }
  225. }()
  226. p.refreshVersion()
  227. p.refreshAPIPort()
  228. return nil
  229. }
  230. // Stop terminates the running Xray process.
  231. func (p *process) Stop() error {
  232. if !p.IsRunning() {
  233. return errors.New("xray is not running")
  234. }
  235. if runtime.GOOS == "windows" {
  236. return p.cmd.Process.Kill()
  237. } else {
  238. return p.cmd.Process.Signal(syscall.SIGTERM)
  239. }
  240. }
  241. // writeCrashReport writes a crash report to the binary folder with a timestamped filename.
  242. func writeCrashReport(m []byte) error {
  243. crashReportPath := config.GetBinFolderPath() + "/core_crash_" + time.Now().Format("20060102_150405") + ".log"
  244. return os.WriteFile(crashReportPath, m, os.ModePerm)
  245. }