process.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. package xray
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "runtime"
  11. "sort"
  12. "strings"
  13. "sync"
  14. "sync/atomic"
  15. "syscall"
  16. "time"
  17. "github.com/mhsanaei/3x-ui/v3/config"
  18. "github.com/mhsanaei/3x-ui/v3/logger"
  19. "github.com/mhsanaei/3x-ui/v3/util/common"
  20. )
  21. // GetBinaryName returns the Xray binary filename for the current OS and architecture.
  22. func GetBinaryName() string {
  23. return fmt.Sprintf("xray-%s-%s", runtime.GOOS, runtime.GOARCH)
  24. }
  25. // GetBinaryPath returns the full path to the Xray binary executable.
  26. func GetBinaryPath() string {
  27. return config.GetBinFolderPath() + "/" + GetBinaryName()
  28. }
  29. // GetConfigPath returns the path to the Xray configuration file in the binary folder.
  30. func GetConfigPath() string {
  31. return config.GetBinFolderPath() + "/config.json"
  32. }
  33. // GetGeositePath returns the path to the geosite data file used by Xray.
  34. func GetGeositePath() string {
  35. return config.GetBinFolderPath() + "/geosite.dat"
  36. }
  37. // GetGeoipPath returns the path to the geoip data file used by Xray.
  38. func GetGeoipPath() string {
  39. return config.GetBinFolderPath() + "/geoip.dat"
  40. }
  41. // GetIPLimitLogPath returns the path to the IP limit log file.
  42. func GetIPLimitLogPath() string {
  43. return config.GetLogFolder() + "/3xipl.log"
  44. }
  45. // GetIPLimitBannedLogPath returns the path to the banned IP log file.
  46. func GetIPLimitBannedLogPath() string {
  47. return config.GetLogFolder() + "/3xipl-banned.log"
  48. }
  49. // GetIPLimitBannedPrevLogPath returns the path to the previous banned IP log file.
  50. func GetIPLimitBannedPrevLogPath() string {
  51. return config.GetLogFolder() + "/3xipl-banned.prev.log"
  52. }
  53. // GetAccessPersistentLogPath returns the path to the persistent access log file.
  54. func GetAccessPersistentLogPath() string {
  55. return config.GetLogFolder() + "/3xipl-ap.log"
  56. }
  57. // GetAccessPersistentPrevLogPath returns the path to the previous persistent access log file.
  58. func GetAccessPersistentPrevLogPath() string {
  59. return config.GetLogFolder() + "/3xipl-ap.prev.log"
  60. }
  61. // GetAccessLogPath reads the Xray config and returns the access log file path.
  62. func GetAccessLogPath() (string, error) {
  63. config, err := os.ReadFile(GetConfigPath())
  64. if err != nil {
  65. logger.Warningf("Failed to read configuration file: %s", err)
  66. return "", err
  67. }
  68. jsonConfig := map[string]any{}
  69. err = json.Unmarshal([]byte(config), &jsonConfig)
  70. if err != nil {
  71. logger.Warningf("Failed to parse JSON configuration: %s", err)
  72. return "", err
  73. }
  74. if jsonConfig["log"] != nil {
  75. jsonLog := jsonConfig["log"].(map[string]any)
  76. if jsonLog["access"] != nil {
  77. accessLogPath := jsonLog["access"].(string)
  78. return accessLogPath, nil
  79. }
  80. }
  81. return "", err
  82. }
  83. // stopProcess calls Stop on the given Process instance.
  84. func stopProcess(p *Process) {
  85. p.Stop()
  86. }
  87. // Process wraps an Xray process instance and provides management methods.
  88. type Process struct {
  89. *process
  90. }
  91. // NewProcess creates a new Xray process and sets up cleanup on garbage collection.
  92. func NewProcess(xrayConfig *Config) *Process {
  93. p := &Process{newProcess(xrayConfig)}
  94. runtime.SetFinalizer(p, stopProcess)
  95. return p
  96. }
  97. // NewTestProcess creates a new Xray process that uses a specific config file path.
  98. // Used for test runs (e.g. outbound test) so the main config.json is not overwritten.
  99. // The config file at configPath is removed when the process is stopped.
  100. func NewTestProcess(xrayConfig *Config, configPath string) *Process {
  101. p := &Process{newTestProcess(xrayConfig, configPath)}
  102. runtime.SetFinalizer(p, stopProcess)
  103. return p
  104. }
  105. type process struct {
  106. cmd *exec.Cmd
  107. done chan struct{}
  108. version string
  109. apiPort int
  110. onlineClients []string
  111. // nodeOnlineClients holds the online-emails list reported by each
  112. // remote node, keyed by node id. NodeTrafficSyncJob populates entries
  113. // per cron tick and clears them when a node's probe fails. The mutex
  114. // guards both this map and onlineClients above so GetOnlineClients
  115. // can build the union without a torn read.
  116. nodeOnlineClients map[int][]string
  117. onlineMu sync.RWMutex
  118. config *Config
  119. configPath string // if set, use this path instead of GetConfigPath() and remove on Stop
  120. logWriter *LogWriter
  121. exitErr error
  122. startTime time.Time
  123. intentionalStop atomic.Bool
  124. }
  125. var (
  126. xrayGracefulStopTimeout = 5 * time.Second
  127. xrayForceStopTimeout = 2 * time.Second
  128. )
  129. // newProcess creates a new internal process struct for Xray.
  130. func newProcess(config *Config) *process {
  131. return &process{
  132. version: "Unknown",
  133. config: config,
  134. logWriter: NewLogWriter(),
  135. startTime: time.Now(),
  136. }
  137. }
  138. // newTestProcess creates a process that writes and runs with a specific config path.
  139. func newTestProcess(config *Config, configPath string) *process {
  140. p := newProcess(config)
  141. p.configPath = configPath
  142. return p
  143. }
  144. // IsRunning returns true if the Xray process is currently running.
  145. func (p *process) IsRunning() bool {
  146. if p.cmd == nil || p.cmd.Process == nil {
  147. return false
  148. }
  149. if p.done != nil {
  150. select {
  151. case <-p.done:
  152. return false
  153. default:
  154. }
  155. }
  156. if p.cmd.ProcessState == nil {
  157. return true
  158. }
  159. return false
  160. }
  161. // GetErr returns the last error encountered by the Xray process.
  162. func (p *process) GetErr() error {
  163. return p.exitErr
  164. }
  165. // GetResult returns the last log line or error from the Xray process.
  166. func (p *process) GetResult() string {
  167. if len(p.logWriter.lastLine) == 0 && p.exitErr != nil {
  168. return p.exitErr.Error()
  169. }
  170. return p.logWriter.lastLine
  171. }
  172. // GetVersion returns the version string of the Xray process.
  173. func (p *process) GetVersion() string {
  174. return p.version
  175. }
  176. // GetAPIPort returns the API port used by the Xray process.
  177. func (p *Process) GetAPIPort() int {
  178. return p.apiPort
  179. }
  180. // GetConfig returns the configuration used by the Xray process.
  181. func (p *Process) GetConfig() *Config {
  182. return p.config
  183. }
  184. // GetOnlineClients returns the union of locally-online clients and
  185. // node-online clients from every registered remote panel. Dedupes by
  186. // email so a client connected to both a local and a node-managed inbound
  187. // surfaces once. Cheap allocation — typical online sets are small and
  188. // the union is recomputed on demand.
  189. func (p *Process) GetOnlineClients() []string {
  190. p.onlineMu.RLock()
  191. defer p.onlineMu.RUnlock()
  192. if len(p.nodeOnlineClients) == 0 {
  193. // Hot path for single-panel deployments: avoid the map+dedupe
  194. // work entirely and return the local slice as-is.
  195. return p.onlineClients
  196. }
  197. seen := make(map[string]struct{}, len(p.onlineClients))
  198. out := make([]string, 0, len(p.onlineClients))
  199. for _, email := range p.onlineClients {
  200. if _, dup := seen[email]; dup {
  201. continue
  202. }
  203. seen[email] = struct{}{}
  204. out = append(out, email)
  205. }
  206. for _, list := range p.nodeOnlineClients {
  207. for _, email := range list {
  208. if _, dup := seen[email]; dup {
  209. continue
  210. }
  211. seen[email] = struct{}{}
  212. out = append(out, email)
  213. }
  214. }
  215. return out
  216. }
  217. // SetOnlineClients sets the locally-online list. Called by the local
  218. // XrayTrafficJob after each xray gRPC stats poll.
  219. func (p *Process) SetOnlineClients(users []string) {
  220. p.onlineMu.Lock()
  221. p.onlineClients = users
  222. p.onlineMu.Unlock()
  223. }
  224. // SetNodeOnlineClients records the online-emails set for one remote
  225. // node. Replaces any previous entry for that node — NodeTrafficSyncJob
  226. // always sends the full list per tick.
  227. func (p *Process) SetNodeOnlineClients(nodeID int, emails []string) {
  228. p.onlineMu.Lock()
  229. defer p.onlineMu.Unlock()
  230. if p.nodeOnlineClients == nil {
  231. p.nodeOnlineClients = map[int][]string{}
  232. }
  233. p.nodeOnlineClients[nodeID] = emails
  234. }
  235. // ClearNodeOnlineClients drops a node's contribution to the online set.
  236. // Called when a probe fails so a downed node doesn't keep its clients
  237. // listed as "online" until the next successful probe.
  238. func (p *Process) ClearNodeOnlineClients(nodeID int) {
  239. p.onlineMu.Lock()
  240. defer p.onlineMu.Unlock()
  241. delete(p.nodeOnlineClients, nodeID)
  242. }
  243. // GetUptime returns the uptime of the Xray process in seconds.
  244. func (p *Process) GetUptime() uint64 {
  245. return uint64(time.Since(p.startTime).Seconds())
  246. }
  247. // refreshAPIPort updates the API port from the inbound configs.
  248. func (p *process) refreshAPIPort() {
  249. for _, inbound := range p.config.InboundConfigs {
  250. if inbound.Tag == "api" {
  251. p.apiPort = inbound.Port
  252. break
  253. }
  254. }
  255. }
  256. // refreshVersion updates the version string by running the Xray binary with -version.
  257. func (p *process) refreshVersion() {
  258. cmd := exec.Command(GetBinaryPath(), "-version")
  259. data, err := cmd.Output()
  260. if err != nil {
  261. p.version = "Unknown"
  262. } else {
  263. datas := bytes.Split(data, []byte(" "))
  264. if len(datas) <= 1 {
  265. p.version = "Unknown"
  266. } else {
  267. p.version = string(datas[1])
  268. }
  269. }
  270. }
  271. // Start launches the Xray process with the current configuration.
  272. func (p *process) Start() (err error) {
  273. if p.IsRunning() {
  274. return errors.New("xray is already running")
  275. }
  276. defer func() {
  277. if err != nil {
  278. logger.Error("Failure in running xray-core process: ", err)
  279. p.exitErr = err
  280. }
  281. }()
  282. data, err := json.MarshalIndent(p.config, "", " ")
  283. if err != nil {
  284. return common.NewErrorf("Failed to generate XRAY configuration files: %v", err)
  285. }
  286. err = os.MkdirAll(config.GetLogFolder(), 0o770)
  287. if err != nil {
  288. logger.Warningf("Failed to create log folder: %s", err)
  289. }
  290. configPath := GetConfigPath()
  291. if p.configPath != "" {
  292. configPath = p.configPath
  293. }
  294. err = os.WriteFile(configPath, data, 0644)
  295. if err != nil {
  296. return common.NewErrorf("Failed to write configuration file: %v", err)
  297. }
  298. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  299. cmd.Stdout = p.logWriter
  300. cmd.Stderr = p.logWriter
  301. err = p.startCommand(cmd)
  302. if err != nil {
  303. return err
  304. }
  305. p.refreshVersion()
  306. p.refreshAPIPort()
  307. return nil
  308. }
  309. func (p *process) startCommand(cmd *exec.Cmd) error {
  310. p.cmd = cmd
  311. p.done = make(chan struct{})
  312. p.exitErr = nil
  313. p.intentionalStop.Store(false)
  314. if err := cmd.Start(); err != nil {
  315. close(p.done)
  316. p.cmd = nil
  317. return err
  318. }
  319. attachChildLifetime(cmd)
  320. go p.waitForCommand(cmd)
  321. return nil
  322. }
  323. func (p *process) waitForCommand(cmd *exec.Cmd) {
  324. defer close(p.done)
  325. err := cmd.Wait()
  326. if err == nil || p.intentionalStop.Load() {
  327. return
  328. }
  329. // On Windows, killing the process results in "exit status 1" which isn't an error for us.
  330. if runtime.GOOS == "windows" {
  331. errStr := strings.ToLower(err.Error())
  332. if strings.Contains(errStr, "exit status 1") {
  333. p.exitErr = err
  334. return
  335. }
  336. }
  337. logger.Error("Failure in running xray-core:", err)
  338. p.exitErr = err
  339. }
  340. // Stop terminates the running Xray process.
  341. func (p *process) Stop() error {
  342. if !p.IsRunning() {
  343. return errors.New("xray is not running")
  344. }
  345. p.intentionalStop.Store(true)
  346. // Remove temporary config file used for test runs so main config is never touched
  347. if p.configPath != "" {
  348. if p.configPath != GetConfigPath() {
  349. // Check if file exists before removing
  350. if _, err := os.Stat(p.configPath); err == nil {
  351. _ = os.Remove(p.configPath)
  352. }
  353. }
  354. }
  355. if runtime.GOOS == "windows" {
  356. if err := p.cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  357. return err
  358. }
  359. return p.waitForExit(xrayForceStopTimeout)
  360. }
  361. if err := p.cmd.Process.Signal(syscall.SIGTERM); err != nil {
  362. if errors.Is(err, os.ErrProcessDone) {
  363. return p.waitForExit(xrayForceStopTimeout)
  364. }
  365. return err
  366. }
  367. if err := p.waitForExit(xrayGracefulStopTimeout); err == nil {
  368. return nil
  369. }
  370. logger.Warning("xray-core did not stop after SIGTERM, killing process")
  371. if err := p.cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  372. return err
  373. }
  374. return p.waitForExit(xrayForceStopTimeout)
  375. }
  376. func (p *process) waitForExit(timeout time.Duration) error {
  377. if p.done == nil {
  378. return nil
  379. }
  380. timer := time.NewTimer(timeout)
  381. defer timer.Stop()
  382. select {
  383. case <-p.done:
  384. return nil
  385. case <-timer.C:
  386. return common.NewErrorf("timed out waiting for xray-core process to stop after %s", timeout)
  387. }
  388. }
  389. const (
  390. crashReportPrefix = "core_crash_"
  391. crashReportSuffix = ".log"
  392. maxCrashReports = 10
  393. )
  394. // writeCrashReport persists a captured xray crash chunk to the log folder
  395. // with nanosecond-precision filename so restart-loop bursts don't overwrite
  396. // each other, and prunes old reports to keep the folder bounded.
  397. func writeCrashReport(m []byte) error {
  398. dir := config.GetLogFolder()
  399. if err := os.MkdirAll(dir, 0o770); err != nil {
  400. return err
  401. }
  402. pruneOldCrashReports(dir, maxCrashReports-1)
  403. name := crashReportPrefix + time.Now().Format("20060102_150405_000000000") + crashReportSuffix
  404. return os.WriteFile(filepath.Join(dir, name), m, 0o640)
  405. }
  406. func pruneOldCrashReports(dir string, keep int) {
  407. entries, err := os.ReadDir(dir)
  408. if err != nil {
  409. return
  410. }
  411. var reports []string
  412. for _, e := range entries {
  413. n := e.Name()
  414. if !e.IsDir() && strings.HasPrefix(n, crashReportPrefix) && strings.HasSuffix(n, crashReportSuffix) {
  415. reports = append(reports, n)
  416. }
  417. }
  418. if len(reports) <= keep {
  419. return
  420. }
  421. sort.Strings(reports)
  422. for _, old := range reports[:len(reports)-keep] {
  423. _ = os.Remove(filepath.Join(dir, old))
  424. }
  425. }