process.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. package xray
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "runtime"
  10. "strings"
  11. "sync"
  12. "syscall"
  13. "time"
  14. "github.com/mhsanaei/3x-ui/v3/config"
  15. "github.com/mhsanaei/3x-ui/v3/logger"
  16. "github.com/mhsanaei/3x-ui/v3/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. // nodeOnlineClients holds the online-emails list reported by each
  108. // remote node, keyed by node id. NodeTrafficSyncJob populates entries
  109. // per cron tick and clears them when a node's probe fails. The mutex
  110. // guards both this map and onlineClients above so GetOnlineClients
  111. // can build the union without a torn read.
  112. nodeOnlineClients map[int][]string
  113. onlineMu sync.RWMutex
  114. config *Config
  115. configPath string // if set, use this path instead of GetConfigPath() and remove on Stop
  116. logWriter *LogWriter
  117. exitErr error
  118. startTime time.Time
  119. }
  120. // newProcess creates a new internal process struct for Xray.
  121. func newProcess(config *Config) *process {
  122. return &process{
  123. version: "Unknown",
  124. config: config,
  125. logWriter: NewLogWriter(),
  126. startTime: time.Now(),
  127. }
  128. }
  129. // newTestProcess creates a process that writes and runs with a specific config path.
  130. func newTestProcess(config *Config, configPath string) *process {
  131. p := newProcess(config)
  132. p.configPath = configPath
  133. return p
  134. }
  135. // IsRunning returns true if the Xray process is currently running.
  136. func (p *process) IsRunning() bool {
  137. if p.cmd == nil || p.cmd.Process == nil {
  138. return false
  139. }
  140. if p.cmd.ProcessState == nil {
  141. return true
  142. }
  143. return false
  144. }
  145. // GetErr returns the last error encountered by the Xray process.
  146. func (p *process) GetErr() error {
  147. return p.exitErr
  148. }
  149. // GetResult returns the last log line or error from the Xray process.
  150. func (p *process) GetResult() string {
  151. if len(p.logWriter.lastLine) == 0 && p.exitErr != nil {
  152. return p.exitErr.Error()
  153. }
  154. return p.logWriter.lastLine
  155. }
  156. // GetVersion returns the version string of the Xray process.
  157. func (p *process) GetVersion() string {
  158. return p.version
  159. }
  160. // GetAPIPort returns the API port used by the Xray process.
  161. func (p *Process) GetAPIPort() int {
  162. return p.apiPort
  163. }
  164. // GetConfig returns the configuration used by the Xray process.
  165. func (p *Process) GetConfig() *Config {
  166. return p.config
  167. }
  168. // GetOnlineClients returns the union of locally-online clients and
  169. // node-online clients from every registered remote panel. Dedupes by
  170. // email so a client connected to both a local and a node-managed inbound
  171. // surfaces once. Cheap allocation — typical online sets are small and
  172. // the union is recomputed on demand.
  173. func (p *Process) GetOnlineClients() []string {
  174. p.onlineMu.RLock()
  175. defer p.onlineMu.RUnlock()
  176. if len(p.nodeOnlineClients) == 0 {
  177. // Hot path for single-panel deployments: avoid the map+dedupe
  178. // work entirely and return the local slice as-is.
  179. return p.onlineClients
  180. }
  181. seen := make(map[string]struct{}, len(p.onlineClients))
  182. out := make([]string, 0, len(p.onlineClients))
  183. for _, email := range p.onlineClients {
  184. if _, dup := seen[email]; dup {
  185. continue
  186. }
  187. seen[email] = struct{}{}
  188. out = append(out, email)
  189. }
  190. for _, list := range p.nodeOnlineClients {
  191. for _, email := range list {
  192. if _, dup := seen[email]; dup {
  193. continue
  194. }
  195. seen[email] = struct{}{}
  196. out = append(out, email)
  197. }
  198. }
  199. return out
  200. }
  201. // SetOnlineClients sets the locally-online list. Called by the local
  202. // XrayTrafficJob after each xray gRPC stats poll.
  203. func (p *Process) SetOnlineClients(users []string) {
  204. p.onlineMu.Lock()
  205. p.onlineClients = users
  206. p.onlineMu.Unlock()
  207. }
  208. // SetNodeOnlineClients records the online-emails set for one remote
  209. // node. Replaces any previous entry for that node — NodeTrafficSyncJob
  210. // always sends the full list per tick.
  211. func (p *Process) SetNodeOnlineClients(nodeID int, emails []string) {
  212. p.onlineMu.Lock()
  213. defer p.onlineMu.Unlock()
  214. if p.nodeOnlineClients == nil {
  215. p.nodeOnlineClients = map[int][]string{}
  216. }
  217. p.nodeOnlineClients[nodeID] = emails
  218. }
  219. // ClearNodeOnlineClients drops a node's contribution to the online set.
  220. // Called when a probe fails so a downed node doesn't keep its clients
  221. // listed as "online" until the next successful probe.
  222. func (p *Process) ClearNodeOnlineClients(nodeID int) {
  223. p.onlineMu.Lock()
  224. defer p.onlineMu.Unlock()
  225. delete(p.nodeOnlineClients, nodeID)
  226. }
  227. // GetUptime returns the uptime of the Xray process in seconds.
  228. func (p *Process) GetUptime() uint64 {
  229. return uint64(time.Since(p.startTime).Seconds())
  230. }
  231. // refreshAPIPort updates the API port from the inbound configs.
  232. func (p *process) refreshAPIPort() {
  233. for _, inbound := range p.config.InboundConfigs {
  234. if inbound.Tag == "api" {
  235. p.apiPort = inbound.Port
  236. break
  237. }
  238. }
  239. }
  240. // refreshVersion updates the version string by running the Xray binary with -version.
  241. func (p *process) refreshVersion() {
  242. cmd := exec.Command(GetBinaryPath(), "-version")
  243. data, err := cmd.Output()
  244. if err != nil {
  245. p.version = "Unknown"
  246. } else {
  247. datas := bytes.Split(data, []byte(" "))
  248. if len(datas) <= 1 {
  249. p.version = "Unknown"
  250. } else {
  251. p.version = string(datas[1])
  252. }
  253. }
  254. }
  255. // Start launches the Xray process with the current configuration.
  256. func (p *process) Start() (err error) {
  257. if p.IsRunning() {
  258. return errors.New("xray is already running")
  259. }
  260. defer func() {
  261. if err != nil {
  262. logger.Error("Failure in running xray-core process: ", err)
  263. p.exitErr = err
  264. }
  265. }()
  266. data, err := json.MarshalIndent(p.config, "", " ")
  267. if err != nil {
  268. return common.NewErrorf("Failed to generate XRAY configuration files: %v", err)
  269. }
  270. err = os.MkdirAll(config.GetLogFolder(), 0o770)
  271. if err != nil {
  272. logger.Warningf("Failed to create log folder: %s", err)
  273. }
  274. configPath := GetConfigPath()
  275. if p.configPath != "" {
  276. configPath = p.configPath
  277. }
  278. err = os.WriteFile(configPath, data, 0644)
  279. if err != nil {
  280. return common.NewErrorf("Failed to write configuration file: %v", err)
  281. }
  282. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  283. p.cmd = cmd
  284. cmd.Stdout = p.logWriter
  285. cmd.Stderr = p.logWriter
  286. go func() {
  287. err := cmd.Run()
  288. if err != nil {
  289. // On Windows, killing the process results in "exit status 1" which isn't an error for us
  290. if runtime.GOOS == "windows" {
  291. errStr := strings.ToLower(err.Error())
  292. if strings.Contains(errStr, "exit status 1") {
  293. // Suppress noisy log on graceful stop
  294. p.exitErr = err
  295. return
  296. }
  297. }
  298. logger.Error("Failure in running xray-core:", err)
  299. p.exitErr = err
  300. }
  301. }()
  302. p.refreshVersion()
  303. p.refreshAPIPort()
  304. return nil
  305. }
  306. // Stop terminates the running Xray process.
  307. func (p *process) Stop() error {
  308. if !p.IsRunning() {
  309. return errors.New("xray is not running")
  310. }
  311. // Remove temporary config file used for test runs so main config is never touched
  312. if p.configPath != "" {
  313. if p.configPath != GetConfigPath() {
  314. // Check if file exists before removing
  315. if _, err := os.Stat(p.configPath); err == nil {
  316. _ = os.Remove(p.configPath)
  317. }
  318. }
  319. }
  320. if runtime.GOOS == "windows" {
  321. return p.cmd.Process.Kill()
  322. } else {
  323. return p.cmd.Process.Signal(syscall.SIGTERM)
  324. }
  325. }
  326. // writeCrashReport writes a crash report to the binary folder with a timestamped filename.
  327. func writeCrashReport(m []byte) error {
  328. crashReportPath := config.GetBinFolderPath() + "/core_crash_" + time.Now().Format("20060102_150405") + ".log"
  329. return os.WriteFile(crashReportPath, m, 0644)
  330. }