process.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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 is the set of emails active on THIS panel's own xray
  111. // within the online grace window. It is derived only from local xray
  112. // traffic polls (see RefreshLocalOnline) — never from remote-node
  113. // snapshots — so a client connected solely to a remote node is not
  114. // reported online on local inbounds.
  115. onlineClients []string
  116. // localLastOnline records, per email, the last time this panel's own
  117. // xray reported traffic for it. RefreshLocalOnline rebuilds
  118. // onlineClients from this map each tick, keeping the local online set
  119. // independent of the shared client_traffics.last_online column — that
  120. // column is bumped by remote-node syncs too and would otherwise leak
  121. // remote-only clients into the local set.
  122. localLastOnline map[string]int64
  123. // nodeOnlineClients holds the online-emails list reported by each
  124. // remote node, keyed by node id. NodeTrafficSyncJob populates entries
  125. // per cron tick and clears them when a node's probe fails. The mutex
  126. // guards this map, onlineClients, and localLastOnline above so the
  127. // online getters never see a torn read.
  128. nodeOnlineClients map[int][]string
  129. onlineMu sync.RWMutex
  130. config *Config
  131. configPath string // if set, use this path instead of GetConfigPath() and remove on Stop
  132. logWriter *LogWriter
  133. exitErr error
  134. startTime time.Time
  135. intentionalStop atomic.Bool
  136. }
  137. var (
  138. xrayGracefulStopTimeout = 5 * time.Second
  139. xrayForceStopTimeout = 2 * time.Second
  140. )
  141. // localNodeKey is the GetOnlineClientsByNode key under which this panel's
  142. // own (non-node-managed) inbounds report their online clients. Node ids
  143. // autoincrement from 1, so 0 is a safe sentinel that never collides with a
  144. // real node. The frontend mirrors this contract (nodeId ?? 0).
  145. const localNodeKey = 0
  146. // newProcess creates a new internal process struct for Xray.
  147. func newProcess(config *Config) *process {
  148. return &process{
  149. version: "Unknown",
  150. config: config,
  151. logWriter: NewLogWriter(),
  152. startTime: time.Now(),
  153. }
  154. }
  155. // newTestProcess creates a process that writes and runs with a specific config path.
  156. func newTestProcess(config *Config, configPath string) *process {
  157. p := newProcess(config)
  158. p.configPath = configPath
  159. return p
  160. }
  161. // IsRunning returns true if the Xray process is currently running.
  162. func (p *process) IsRunning() bool {
  163. if p.cmd == nil || p.cmd.Process == nil {
  164. return false
  165. }
  166. if p.done != nil {
  167. select {
  168. case <-p.done:
  169. return false
  170. default:
  171. }
  172. }
  173. if p.cmd.ProcessState == nil {
  174. return true
  175. }
  176. return false
  177. }
  178. // GetErr returns the last error encountered by the Xray process.
  179. func (p *process) GetErr() error {
  180. return p.exitErr
  181. }
  182. // GetResult returns the last log line or error from the Xray process.
  183. func (p *process) GetResult() string {
  184. if len(p.logWriter.lastLine) == 0 && p.exitErr != nil {
  185. return p.exitErr.Error()
  186. }
  187. return p.logWriter.lastLine
  188. }
  189. // GetVersion returns the version string of the Xray process.
  190. func (p *process) GetVersion() string {
  191. return p.version
  192. }
  193. // GetAPIPort returns the API port used by the Xray process.
  194. func (p *Process) GetAPIPort() int {
  195. return p.apiPort
  196. }
  197. // GetConfig returns the configuration used by the Xray process.
  198. func (p *Process) GetConfig() *Config {
  199. return p.config
  200. }
  201. // GetOnlineClients returns the union of locally-online clients and
  202. // node-online clients from every registered remote panel. Dedupes by
  203. // email so a client connected to both a local and a node-managed inbound
  204. // surfaces once. Cheap allocation — typical online sets are small and
  205. // the union is recomputed on demand.
  206. func (p *Process) GetOnlineClients() []string {
  207. p.onlineMu.RLock()
  208. defer p.onlineMu.RUnlock()
  209. if len(p.nodeOnlineClients) == 0 {
  210. // Hot path for single-panel deployments: avoid the map+dedupe
  211. // work entirely and return the local slice as-is.
  212. return p.onlineClients
  213. }
  214. seen := make(map[string]struct{}, len(p.onlineClients))
  215. out := make([]string, 0, len(p.onlineClients))
  216. for _, email := range p.onlineClients {
  217. if _, dup := seen[email]; dup {
  218. continue
  219. }
  220. seen[email] = struct{}{}
  221. out = append(out, email)
  222. }
  223. for _, list := range p.nodeOnlineClients {
  224. for _, email := range list {
  225. if _, dup := seen[email]; dup {
  226. continue
  227. }
  228. seen[email] = struct{}{}
  229. out = append(out, email)
  230. }
  231. }
  232. return out
  233. }
  234. // GetOnlineClientsByNode returns online emails grouped by the node that
  235. // reported them: this panel's own xray clients under localNodeKey (0), and
  236. // each remote node's clients under that node's id. Unlike GetOnlineClients
  237. // (which flattens everything into one deduped union), this preserves node
  238. // attribution so per-inbound/per-node online counts don't bleed a client
  239. // connected to one node onto every other node. Empty groups are omitted.
  240. func (p *Process) GetOnlineClientsByNode() map[int][]string {
  241. p.onlineMu.RLock()
  242. defer p.onlineMu.RUnlock()
  243. out := make(map[int][]string, len(p.nodeOnlineClients)+1)
  244. if len(p.onlineClients) > 0 {
  245. local := make([]string, len(p.onlineClients))
  246. copy(local, p.onlineClients)
  247. out[localNodeKey] = local
  248. }
  249. for nodeID, list := range p.nodeOnlineClients {
  250. if len(list) == 0 {
  251. continue
  252. }
  253. cp := make([]string, len(list))
  254. copy(cp, list)
  255. out[nodeID] = cp
  256. }
  257. return out
  258. }
  259. // RefreshLocalOnline records that each email in activeEmails had local xray
  260. // traffic at now, then rebuilds onlineClients from every email seen within
  261. // graceMs and prunes entries older than that. Called by the local
  262. // XrayTrafficJob after each xray gRPC stats poll. Pass a nil/empty
  263. // activeEmails to only prune — NodeTrafficSyncJob does this so a stopped
  264. // local xray's clients still age out between local traffic polls.
  265. func (p *Process) RefreshLocalOnline(activeEmails []string, now, graceMs int64) {
  266. p.onlineMu.Lock()
  267. defer p.onlineMu.Unlock()
  268. if p.localLastOnline == nil {
  269. p.localLastOnline = make(map[string]int64, len(activeEmails))
  270. }
  271. for _, email := range activeEmails {
  272. p.localLastOnline[email] = now
  273. }
  274. online := make([]string, 0, len(p.localLastOnline))
  275. for email, ts := range p.localLastOnline {
  276. if now-ts < graceMs {
  277. online = append(online, email)
  278. } else {
  279. delete(p.localLastOnline, email)
  280. }
  281. }
  282. p.onlineClients = online
  283. }
  284. // SetNodeOnlineClients records the online-emails set for one remote
  285. // node. Replaces any previous entry for that node — NodeTrafficSyncJob
  286. // always sends the full list per tick.
  287. func (p *Process) SetNodeOnlineClients(nodeID int, emails []string) {
  288. p.onlineMu.Lock()
  289. defer p.onlineMu.Unlock()
  290. if p.nodeOnlineClients == nil {
  291. p.nodeOnlineClients = map[int][]string{}
  292. }
  293. p.nodeOnlineClients[nodeID] = emails
  294. }
  295. // ClearNodeOnlineClients drops a node's contribution to the online set.
  296. // Called when a probe fails so a downed node doesn't keep its clients
  297. // listed as "online" until the next successful probe.
  298. func (p *Process) ClearNodeOnlineClients(nodeID int) {
  299. p.onlineMu.Lock()
  300. defer p.onlineMu.Unlock()
  301. delete(p.nodeOnlineClients, nodeID)
  302. }
  303. // GetUptime returns the uptime of the Xray process in seconds.
  304. func (p *Process) GetUptime() uint64 {
  305. return uint64(time.Since(p.startTime).Seconds())
  306. }
  307. // refreshAPIPort updates the API port from the inbound configs.
  308. func (p *process) refreshAPIPort() {
  309. for _, inbound := range p.config.InboundConfigs {
  310. if inbound.Tag == "api" {
  311. p.apiPort = inbound.Port
  312. break
  313. }
  314. }
  315. }
  316. // refreshVersion updates the version string by running the Xray binary with -version.
  317. func (p *process) refreshVersion() {
  318. cmd := exec.Command(GetBinaryPath(), "-version")
  319. data, err := cmd.Output()
  320. if err != nil {
  321. p.version = "Unknown"
  322. } else {
  323. datas := bytes.Split(data, []byte(" "))
  324. if len(datas) <= 1 {
  325. p.version = "Unknown"
  326. } else {
  327. p.version = string(datas[1])
  328. }
  329. }
  330. }
  331. // Start launches the Xray process with the current configuration.
  332. func (p *process) Start() (err error) {
  333. if p.IsRunning() {
  334. return errors.New("xray is already running")
  335. }
  336. defer func() {
  337. if err != nil {
  338. logger.Error("Failure in running xray-core process: ", err)
  339. p.exitErr = err
  340. }
  341. }()
  342. data, err := json.MarshalIndent(p.config, "", " ")
  343. if err != nil {
  344. return common.NewErrorf("Failed to generate XRAY configuration files: %v", err)
  345. }
  346. err = os.MkdirAll(config.GetLogFolder(), 0o770)
  347. if err != nil {
  348. logger.Warningf("Failed to create log folder: %s", err)
  349. }
  350. configPath := GetConfigPath()
  351. if p.configPath != "" {
  352. configPath = p.configPath
  353. }
  354. err = os.WriteFile(configPath, data, 0644)
  355. if err != nil {
  356. return common.NewErrorf("Failed to write configuration file: %v", err)
  357. }
  358. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  359. cmd.Stdout = p.logWriter
  360. cmd.Stderr = p.logWriter
  361. err = p.startCommand(cmd)
  362. if err != nil {
  363. return err
  364. }
  365. p.refreshVersion()
  366. p.refreshAPIPort()
  367. return nil
  368. }
  369. func (p *process) startCommand(cmd *exec.Cmd) error {
  370. p.cmd = cmd
  371. p.done = make(chan struct{})
  372. p.exitErr = nil
  373. p.intentionalStop.Store(false)
  374. if err := cmd.Start(); err != nil {
  375. close(p.done)
  376. p.cmd = nil
  377. return err
  378. }
  379. attachChildLifetime(cmd)
  380. go p.waitForCommand(cmd)
  381. return nil
  382. }
  383. func (p *process) waitForCommand(cmd *exec.Cmd) {
  384. defer close(p.done)
  385. err := cmd.Wait()
  386. if err == nil || p.intentionalStop.Load() {
  387. return
  388. }
  389. // On Windows, killing the process results in "exit status 1" which isn't an error for us.
  390. if runtime.GOOS == "windows" {
  391. errStr := strings.ToLower(err.Error())
  392. if strings.Contains(errStr, "exit status 1") {
  393. p.exitErr = err
  394. return
  395. }
  396. }
  397. logger.Error("Failure in running xray-core:", err)
  398. p.exitErr = err
  399. }
  400. // Stop terminates the running Xray process.
  401. func (p *process) Stop() error {
  402. if !p.IsRunning() {
  403. return errors.New("xray is not running")
  404. }
  405. p.intentionalStop.Store(true)
  406. // Remove temporary config file used for test runs so main config is never touched
  407. if p.configPath != "" {
  408. if p.configPath != GetConfigPath() {
  409. // Check if file exists before removing
  410. if _, err := os.Stat(p.configPath); err == nil {
  411. _ = os.Remove(p.configPath)
  412. }
  413. }
  414. }
  415. if runtime.GOOS == "windows" {
  416. if err := p.cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  417. return err
  418. }
  419. return p.waitForExit(xrayForceStopTimeout)
  420. }
  421. if err := p.cmd.Process.Signal(syscall.SIGTERM); err != nil {
  422. if errors.Is(err, os.ErrProcessDone) {
  423. return p.waitForExit(xrayForceStopTimeout)
  424. }
  425. return err
  426. }
  427. if err := p.waitForExit(xrayGracefulStopTimeout); err == nil {
  428. return nil
  429. }
  430. logger.Warning("xray-core did not stop after SIGTERM, killing process")
  431. if err := p.cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  432. return err
  433. }
  434. return p.waitForExit(xrayForceStopTimeout)
  435. }
  436. func (p *process) waitForExit(timeout time.Duration) error {
  437. if p.done == nil {
  438. return nil
  439. }
  440. timer := time.NewTimer(timeout)
  441. defer timer.Stop()
  442. select {
  443. case <-p.done:
  444. return nil
  445. case <-timer.C:
  446. return common.NewErrorf("timed out waiting for xray-core process to stop after %s", timeout)
  447. }
  448. }
  449. const (
  450. crashReportPrefix = "core_crash_"
  451. crashReportSuffix = ".log"
  452. maxCrashReports = 10
  453. )
  454. // writeCrashReport persists a captured xray crash chunk to the log folder
  455. // with nanosecond-precision filename so restart-loop bursts don't overwrite
  456. // each other, and prunes old reports to keep the folder bounded.
  457. func writeCrashReport(m []byte) error {
  458. dir := config.GetLogFolder()
  459. if err := os.MkdirAll(dir, 0o770); err != nil {
  460. return err
  461. }
  462. pruneOldCrashReports(dir, maxCrashReports-1)
  463. name := crashReportPrefix + time.Now().Format("20060102_150405_000000000") + crashReportSuffix
  464. return os.WriteFile(filepath.Join(dir, name), m, 0o640)
  465. }
  466. func pruneOldCrashReports(dir string, keep int) {
  467. entries, err := os.ReadDir(dir)
  468. if err != nil {
  469. return
  470. }
  471. var reports []string
  472. for _, e := range entries {
  473. n := e.Name()
  474. if !e.IsDir() && strings.HasPrefix(n, crashReportPrefix) && strings.HasSuffix(n, crashReportSuffix) {
  475. reports = append(reports, n)
  476. }
  477. }
  478. if len(reports) <= keep {
  479. return
  480. }
  481. sort.Strings(reports)
  482. for _, old := range reports[:len(reports)-keep] {
  483. _ = os.Remove(filepath.Join(dir, old))
  484. }
  485. }