process.go 17 KB

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