1
0

process.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. // NewTestProcess creates a new Xray process that uses a specific config file path.
  95. // Used for test runs (e.g. outbound test) so the main config.json is not overwritten.
  96. // The config file at configPath is removed when the process is stopped.
  97. func NewTestProcess(xrayConfig *Config, configPath string) *Process {
  98. p := &Process{newTestProcess(xrayConfig, configPath)}
  99. runtime.SetFinalizer(p, stopProcess)
  100. return p
  101. }
  102. type process struct {
  103. cmd *exec.Cmd
  104. version string
  105. apiPort int
  106. onlineClients []string
  107. config *Config
  108. configPath string // if set, use this path instead of GetConfigPath() and remove on Stop
  109. logWriter *LogWriter
  110. exitErr error
  111. startTime time.Time
  112. }
  113. // newProcess creates a new internal process struct for Xray.
  114. func newProcess(config *Config) *process {
  115. return &process{
  116. version: "Unknown",
  117. config: config,
  118. logWriter: NewLogWriter(),
  119. startTime: time.Now(),
  120. }
  121. }
  122. // newTestProcess creates a process that writes and runs with a specific config path.
  123. func newTestProcess(config *Config, configPath string) *process {
  124. p := newProcess(config)
  125. p.configPath = configPath
  126. return p
  127. }
  128. // IsRunning returns true if the Xray process is currently running.
  129. func (p *process) IsRunning() bool {
  130. if p.cmd == nil || p.cmd.Process == nil {
  131. return false
  132. }
  133. if p.cmd.ProcessState == nil {
  134. return true
  135. }
  136. return false
  137. }
  138. // GetErr returns the last error encountered by the Xray process.
  139. func (p *process) GetErr() error {
  140. return p.exitErr
  141. }
  142. // GetResult returns the last log line or error from the Xray process.
  143. func (p *process) GetResult() string {
  144. if len(p.logWriter.lastLine) == 0 && p.exitErr != nil {
  145. return p.exitErr.Error()
  146. }
  147. return p.logWriter.lastLine
  148. }
  149. // GetVersion returns the version string of the Xray process.
  150. func (p *process) GetVersion() string {
  151. return p.version
  152. }
  153. // GetAPIPort returns the API port used by the Xray process.
  154. func (p *Process) GetAPIPort() int {
  155. return p.apiPort
  156. }
  157. // GetConfig returns the configuration used by the Xray process.
  158. func (p *Process) GetConfig() *Config {
  159. return p.config
  160. }
  161. // GetOnlineClients returns the list of online clients for the Xray process.
  162. func (p *Process) GetOnlineClients() []string {
  163. return p.onlineClients
  164. }
  165. // SetOnlineClients sets the list of online clients for the Xray process.
  166. func (p *Process) SetOnlineClients(users []string) {
  167. p.onlineClients = users
  168. }
  169. // GetUptime returns the uptime of the Xray process in seconds.
  170. func (p *Process) GetUptime() uint64 {
  171. return uint64(time.Since(p.startTime).Seconds())
  172. }
  173. // refreshAPIPort updates the API port from the inbound configs.
  174. func (p *process) refreshAPIPort() {
  175. for _, inbound := range p.config.InboundConfigs {
  176. if inbound.Tag == "api" {
  177. p.apiPort = inbound.Port
  178. break
  179. }
  180. }
  181. }
  182. // refreshVersion updates the version string by running the Xray binary with -version.
  183. func (p *process) refreshVersion() {
  184. cmd := exec.Command(GetBinaryPath(), "-version")
  185. data, err := cmd.Output()
  186. if err != nil {
  187. p.version = "Unknown"
  188. } else {
  189. datas := bytes.Split(data, []byte(" "))
  190. if len(datas) <= 1 {
  191. p.version = "Unknown"
  192. } else {
  193. p.version = string(datas[1])
  194. }
  195. }
  196. }
  197. // Start launches the Xray process with the current configuration.
  198. func (p *process) Start() (err error) {
  199. if p.IsRunning() {
  200. return errors.New("xray is already running")
  201. }
  202. defer func() {
  203. if err != nil {
  204. logger.Error("Failure in running xray-core process: ", err)
  205. p.exitErr = err
  206. }
  207. }()
  208. data, err := json.MarshalIndent(p.config, "", " ")
  209. if err != nil {
  210. return common.NewErrorf("Failed to generate XRAY configuration files: %v", err)
  211. }
  212. err = os.MkdirAll(config.GetLogFolder(), 0o770)
  213. if err != nil {
  214. logger.Warningf("Failed to create log folder: %s", err)
  215. }
  216. configPath := GetConfigPath()
  217. if p.configPath != "" {
  218. configPath = p.configPath
  219. }
  220. err = os.WriteFile(configPath, data, fs.ModePerm)
  221. if err != nil {
  222. return common.NewErrorf("Failed to write configuration file: %v", err)
  223. }
  224. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  225. p.cmd = cmd
  226. cmd.Stdout = p.logWriter
  227. cmd.Stderr = p.logWriter
  228. go func() {
  229. err := cmd.Run()
  230. if err != nil {
  231. // On Windows, killing the process results in "exit status 1" which isn't an error for us
  232. if runtime.GOOS == "windows" {
  233. errStr := strings.ToLower(err.Error())
  234. if strings.Contains(errStr, "exit status 1") {
  235. // Suppress noisy log on graceful stop
  236. p.exitErr = err
  237. return
  238. }
  239. }
  240. logger.Error("Failure in running xray-core:", err)
  241. p.exitErr = err
  242. }
  243. }()
  244. p.refreshVersion()
  245. p.refreshAPIPort()
  246. return nil
  247. }
  248. // Stop terminates the running Xray process.
  249. func (p *process) Stop() error {
  250. if !p.IsRunning() {
  251. return errors.New("xray is not running")
  252. }
  253. // Remove temporary config file used for test runs so main config is never touched
  254. if p.configPath != "" {
  255. if p.configPath != GetConfigPath() {
  256. // Check if file exists before removing
  257. if _, err := os.Stat(p.configPath); err == nil {
  258. _ = os.Remove(p.configPath)
  259. }
  260. }
  261. }
  262. if runtime.GOOS == "windows" {
  263. return p.cmd.Process.Kill()
  264. } else {
  265. return p.cmd.Process.Signal(syscall.SIGTERM)
  266. }
  267. }
  268. // writeCrashReport writes a crash report to the binary folder with a timestamped filename.
  269. func writeCrashReport(m []byte) error {
  270. crashReportPath := config.GetBinFolderPath() + "/core_crash_" + time.Now().Format("20060102_150405") + ".log"
  271. return os.WriteFile(crashReportPath, m, os.ModePerm)
  272. }