process.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. "sync"
  13. "syscall"
  14. "time"
  15. "github.com/mhsanaei/3x-ui/v3/config"
  16. "github.com/mhsanaei/3x-ui/v3/logger"
  17. "github.com/mhsanaei/3x-ui/v3/util/common"
  18. )
  19. // GetBinaryName returns the Xray binary filename for the current OS and architecture.
  20. func GetBinaryName() string {
  21. return fmt.Sprintf("xray-%s-%s", runtime.GOOS, runtime.GOARCH)
  22. }
  23. // GetBinaryPath returns the full path to the Xray binary executable.
  24. func GetBinaryPath() string {
  25. return config.GetBinFolderPath() + "/" + GetBinaryName()
  26. }
  27. // GetConfigPath returns the path to the Xray configuration file in the binary folder.
  28. func GetConfigPath() string {
  29. return config.GetBinFolderPath() + "/config.json"
  30. }
  31. // GetGeositePath returns the path to the geosite data file used by Xray.
  32. func GetGeositePath() string {
  33. return config.GetBinFolderPath() + "/geosite.dat"
  34. }
  35. // GetGeoipPath returns the path to the geoip data file used by Xray.
  36. func GetGeoipPath() string {
  37. return config.GetBinFolderPath() + "/geoip.dat"
  38. }
  39. // GetIPLimitLogPath returns the path to the IP limit log file.
  40. func GetIPLimitLogPath() string {
  41. return config.GetLogFolder() + "/3xipl.log"
  42. }
  43. // GetIPLimitBannedLogPath returns the path to the banned IP log file.
  44. func GetIPLimitBannedLogPath() string {
  45. return config.GetLogFolder() + "/3xipl-banned.log"
  46. }
  47. // GetIPLimitBannedPrevLogPath returns the path to the previous banned IP log file.
  48. func GetIPLimitBannedPrevLogPath() string {
  49. return config.GetLogFolder() + "/3xipl-banned.prev.log"
  50. }
  51. // GetAccessPersistentLogPath returns the path to the persistent access log file.
  52. func GetAccessPersistentLogPath() string {
  53. return config.GetLogFolder() + "/3xipl-ap.log"
  54. }
  55. // GetAccessPersistentPrevLogPath returns the path to the previous persistent access log file.
  56. func GetAccessPersistentPrevLogPath() string {
  57. return config.GetLogFolder() + "/3xipl-ap.prev.log"
  58. }
  59. // GetAccessLogPath reads the Xray config and returns the access log file path.
  60. func GetAccessLogPath() (string, error) {
  61. config, err := os.ReadFile(GetConfigPath())
  62. if err != nil {
  63. logger.Warningf("Failed to read configuration file: %s", err)
  64. return "", err
  65. }
  66. jsonConfig := map[string]any{}
  67. err = json.Unmarshal([]byte(config), &jsonConfig)
  68. if err != nil {
  69. logger.Warningf("Failed to parse JSON configuration: %s", err)
  70. return "", err
  71. }
  72. if jsonConfig["log"] != nil {
  73. jsonLog := jsonConfig["log"].(map[string]any)
  74. if jsonLog["access"] != nil {
  75. accessLogPath := jsonLog["access"].(string)
  76. return accessLogPath, nil
  77. }
  78. }
  79. return "", err
  80. }
  81. // stopProcess calls Stop on the given Process instance.
  82. func stopProcess(p *Process) {
  83. p.Stop()
  84. }
  85. // Process wraps an Xray process instance and provides management methods.
  86. type Process struct {
  87. *process
  88. }
  89. // NewProcess creates a new Xray process and sets up cleanup on garbage collection.
  90. func NewProcess(xrayConfig *Config) *Process {
  91. p := &Process{newProcess(xrayConfig)}
  92. runtime.SetFinalizer(p, stopProcess)
  93. return p
  94. }
  95. // NewTestProcess creates a new Xray process that uses a specific config file path.
  96. // Used for test runs (e.g. outbound test) so the main config.json is not overwritten.
  97. // The config file at configPath is removed when the process is stopped.
  98. func NewTestProcess(xrayConfig *Config, configPath string) *Process {
  99. p := &Process{newTestProcess(xrayConfig, configPath)}
  100. runtime.SetFinalizer(p, stopProcess)
  101. return p
  102. }
  103. type process struct {
  104. cmd *exec.Cmd
  105. version string
  106. apiPort int
  107. onlineClients []string
  108. // nodeOnlineClients holds the online-emails list reported by each
  109. // remote node, keyed by node id. NodeTrafficSyncJob populates entries
  110. // per cron tick and clears them when a node's probe fails. The mutex
  111. // guards both this map and onlineClients above so GetOnlineClients
  112. // can build the union without a torn read.
  113. nodeOnlineClients map[int][]string
  114. onlineMu sync.RWMutex
  115. config *Config
  116. configPath string // if set, use this path instead of GetConfigPath() and remove on Stop
  117. logWriter *LogWriter
  118. exitErr error
  119. startTime time.Time
  120. }
  121. // newProcess creates a new internal process struct for Xray.
  122. func newProcess(config *Config) *process {
  123. return &process{
  124. version: "Unknown",
  125. config: config,
  126. logWriter: NewLogWriter(),
  127. startTime: time.Now(),
  128. }
  129. }
  130. // newTestProcess creates a process that writes and runs with a specific config path.
  131. func newTestProcess(config *Config, configPath string) *process {
  132. p := newProcess(config)
  133. p.configPath = configPath
  134. return p
  135. }
  136. // IsRunning returns true if the Xray process is currently running.
  137. func (p *process) IsRunning() bool {
  138. if p.cmd == nil || p.cmd.Process == nil {
  139. return false
  140. }
  141. if p.cmd.ProcessState == nil {
  142. return true
  143. }
  144. return false
  145. }
  146. // GetErr returns the last error encountered by the Xray process.
  147. func (p *process) GetErr() error {
  148. return p.exitErr
  149. }
  150. // GetResult returns the last log line or error from the Xray process.
  151. func (p *process) GetResult() string {
  152. if len(p.logWriter.lastLine) == 0 && p.exitErr != nil {
  153. return p.exitErr.Error()
  154. }
  155. return p.logWriter.lastLine
  156. }
  157. // GetVersion returns the version string of the Xray process.
  158. func (p *process) GetVersion() string {
  159. return p.version
  160. }
  161. // GetAPIPort returns the API port used by the Xray process.
  162. func (p *Process) GetAPIPort() int {
  163. return p.apiPort
  164. }
  165. // GetConfig returns the configuration used by the Xray process.
  166. func (p *Process) GetConfig() *Config {
  167. return p.config
  168. }
  169. // GetOnlineClients returns the union of locally-online clients and
  170. // node-online clients from every registered remote panel. Dedupes by
  171. // email so a client connected to both a local and a node-managed inbound
  172. // surfaces once. Cheap allocation — typical online sets are small and
  173. // the union is recomputed on demand.
  174. func (p *Process) GetOnlineClients() []string {
  175. p.onlineMu.RLock()
  176. defer p.onlineMu.RUnlock()
  177. if len(p.nodeOnlineClients) == 0 {
  178. // Hot path for single-panel deployments: avoid the map+dedupe
  179. // work entirely and return the local slice as-is.
  180. return p.onlineClients
  181. }
  182. seen := make(map[string]struct{}, len(p.onlineClients))
  183. out := make([]string, 0, len(p.onlineClients))
  184. for _, email := range p.onlineClients {
  185. if _, dup := seen[email]; dup {
  186. continue
  187. }
  188. seen[email] = struct{}{}
  189. out = append(out, email)
  190. }
  191. for _, list := range p.nodeOnlineClients {
  192. for _, email := range list {
  193. if _, dup := seen[email]; dup {
  194. continue
  195. }
  196. seen[email] = struct{}{}
  197. out = append(out, email)
  198. }
  199. }
  200. return out
  201. }
  202. // SetOnlineClients sets the locally-online list. Called by the local
  203. // XrayTrafficJob after each xray gRPC stats poll.
  204. func (p *Process) SetOnlineClients(users []string) {
  205. p.onlineMu.Lock()
  206. p.onlineClients = users
  207. p.onlineMu.Unlock()
  208. }
  209. // SetNodeOnlineClients records the online-emails set for one remote
  210. // node. Replaces any previous entry for that node — NodeTrafficSyncJob
  211. // always sends the full list per tick.
  212. func (p *Process) SetNodeOnlineClients(nodeID int, emails []string) {
  213. p.onlineMu.Lock()
  214. defer p.onlineMu.Unlock()
  215. if p.nodeOnlineClients == nil {
  216. p.nodeOnlineClients = map[int][]string{}
  217. }
  218. p.nodeOnlineClients[nodeID] = emails
  219. }
  220. // ClearNodeOnlineClients drops a node's contribution to the online set.
  221. // Called when a probe fails so a downed node doesn't keep its clients
  222. // listed as "online" until the next successful probe.
  223. func (p *Process) ClearNodeOnlineClients(nodeID int) {
  224. p.onlineMu.Lock()
  225. defer p.onlineMu.Unlock()
  226. delete(p.nodeOnlineClients, nodeID)
  227. }
  228. // GetUptime returns the uptime of the Xray process in seconds.
  229. func (p *Process) GetUptime() uint64 {
  230. return uint64(time.Since(p.startTime).Seconds())
  231. }
  232. // refreshAPIPort updates the API port from the inbound configs.
  233. func (p *process) refreshAPIPort() {
  234. for _, inbound := range p.config.InboundConfigs {
  235. if inbound.Tag == "api" {
  236. p.apiPort = inbound.Port
  237. break
  238. }
  239. }
  240. }
  241. // refreshVersion updates the version string by running the Xray binary with -version.
  242. func (p *process) refreshVersion() {
  243. cmd := exec.Command(GetBinaryPath(), "-version")
  244. data, err := cmd.Output()
  245. if err != nil {
  246. p.version = "Unknown"
  247. } else {
  248. datas := bytes.Split(data, []byte(" "))
  249. if len(datas) <= 1 {
  250. p.version = "Unknown"
  251. } else {
  252. p.version = string(datas[1])
  253. }
  254. }
  255. }
  256. // Start launches the Xray process with the current configuration.
  257. func (p *process) Start() (err error) {
  258. if p.IsRunning() {
  259. return errors.New("xray is already running")
  260. }
  261. defer func() {
  262. if err != nil {
  263. logger.Error("Failure in running xray-core process: ", err)
  264. p.exitErr = err
  265. }
  266. }()
  267. data, err := json.MarshalIndent(p.config, "", " ")
  268. if err != nil {
  269. return common.NewErrorf("Failed to generate XRAY configuration files: %v", err)
  270. }
  271. err = os.MkdirAll(config.GetLogFolder(), 0o770)
  272. if err != nil {
  273. logger.Warningf("Failed to create log folder: %s", err)
  274. }
  275. configPath := GetConfigPath()
  276. if p.configPath != "" {
  277. configPath = p.configPath
  278. }
  279. err = os.WriteFile(configPath, data, fs.ModePerm)
  280. if err != nil {
  281. return common.NewErrorf("Failed to write configuration file: %v", err)
  282. }
  283. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  284. p.cmd = cmd
  285. cmd.Stdout = p.logWriter
  286. cmd.Stderr = p.logWriter
  287. go func() {
  288. err := cmd.Run()
  289. if err != nil {
  290. // On Windows, killing the process results in "exit status 1" which isn't an error for us
  291. if runtime.GOOS == "windows" {
  292. errStr := strings.ToLower(err.Error())
  293. if strings.Contains(errStr, "exit status 1") {
  294. // Suppress noisy log on graceful stop
  295. p.exitErr = err
  296. return
  297. }
  298. }
  299. logger.Error("Failure in running xray-core:", err)
  300. p.exitErr = err
  301. }
  302. }()
  303. p.refreshVersion()
  304. p.refreshAPIPort()
  305. return nil
  306. }
  307. // Stop terminates the running Xray process.
  308. func (p *process) Stop() error {
  309. if !p.IsRunning() {
  310. return errors.New("xray is not running")
  311. }
  312. // Remove temporary config file used for test runs so main config is never touched
  313. if p.configPath != "" {
  314. if p.configPath != GetConfigPath() {
  315. // Check if file exists before removing
  316. if _, err := os.Stat(p.configPath); err == nil {
  317. _ = os.Remove(p.configPath)
  318. }
  319. }
  320. }
  321. if runtime.GOOS == "windows" {
  322. return p.cmd.Process.Kill()
  323. } else {
  324. return p.cmd.Process.Signal(syscall.SIGTERM)
  325. }
  326. }
  327. // writeCrashReport writes a crash report to the binary folder with a timestamped filename.
  328. func writeCrashReport(m []byte) error {
  329. crashReportPath := config.GetBinFolderPath() + "/core_crash_" + time.Now().Format("20060102_150405") + ".log"
  330. return os.WriteFile(crashReportPath, m, os.ModePerm)
  331. }