process.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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. // nodeOnlineTrees holds, per direct remote node (keyed by that node's
  137. // panel-local id), the GUID-keyed online-emails subtree that node
  138. // reported — its own clients under its panelGuid plus every descendant
  139. // under theirs. Keying the stored value by GUID (not node id) lets the
  140. // master attribute a deeply nested client to the node that physically
  141. // hosts it across a chain (#4983); the outer node-id key is only so a
  142. // failed probe can drop that whole branch's contribution. NodeTrafficSyncJob
  143. // populates entries per cron tick and clears them when a probe fails. The
  144. // mutex guards this map, onlineClients, and localLastOnline above so the
  145. // online getters never see a torn read.
  146. nodeOnlineTrees map[int]map[string][]string
  147. onlineMu sync.RWMutex
  148. config *Config
  149. configPath string // if set, use this path instead of GetConfigPath() and remove on Stop
  150. logWriter *LogWriter
  151. exitErr error
  152. startTime time.Time
  153. intentionalStop atomic.Bool
  154. }
  155. var (
  156. xrayGracefulStopTimeout = 5 * time.Second
  157. xrayForceStopTimeout = 2 * time.Second
  158. )
  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.nodeOnlineTrees) == 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. add := func(emails []string) {
  230. for _, email := range emails {
  231. if _, dup := seen[email]; dup {
  232. continue
  233. }
  234. seen[email] = struct{}{}
  235. out = append(out, email)
  236. }
  237. }
  238. add(p.onlineClients)
  239. for _, tree := range p.nodeOnlineTrees {
  240. for _, emails := range tree {
  241. add(emails)
  242. }
  243. }
  244. return out
  245. }
  246. // GetLocalOnlineClients returns a copy of the emails online on THIS panel's own
  247. // xray within the grace window. The service layer keys these under the panel's
  248. // own GUID when assembling the per-node online view.
  249. func (p *Process) GetLocalOnlineClients() []string {
  250. p.onlineMu.RLock()
  251. defer p.onlineMu.RUnlock()
  252. if len(p.onlineClients) == 0 {
  253. return nil
  254. }
  255. out := make([]string, len(p.onlineClients))
  256. copy(out, p.onlineClients)
  257. return out
  258. }
  259. // GetMergedNodeTrees returns the union of every direct node's reported subtree,
  260. // keyed by the panelGuid of the node that physically hosts each client set.
  261. // Because each child already reports its descendants under their own GUIDs,
  262. // merging the direct children yields the whole tree at any depth (#4983), so a
  263. // client three hops down is attributed to its real node, not the intermediate
  264. // one. GUIDs are globally unique, but a set reported under the same GUID by more
  265. // than one path is deduped per key; empty sets are omitted.
  266. func (p *Process) GetMergedNodeTrees() map[string][]string {
  267. p.onlineMu.RLock()
  268. defer p.onlineMu.RUnlock()
  269. if len(p.nodeOnlineTrees) == 0 {
  270. return map[string][]string{}
  271. }
  272. out := make(map[string][]string)
  273. seen := make(map[string]map[string]struct{})
  274. for _, tree := range p.nodeOnlineTrees {
  275. for guid, emails := range tree {
  276. if guid == "" || len(emails) == 0 {
  277. continue
  278. }
  279. dedup := seen[guid]
  280. if dedup == nil {
  281. dedup = make(map[string]struct{}, len(emails))
  282. seen[guid] = dedup
  283. }
  284. for _, email := range emails {
  285. if _, ok := dedup[email]; ok {
  286. continue
  287. }
  288. dedup[email] = struct{}{}
  289. out[guid] = append(out[guid], email)
  290. }
  291. }
  292. }
  293. return out
  294. }
  295. // GetLocalActiveInbounds returns a copy of THIS panel's inbound tags that
  296. // carried traffic within the grace window. Only the local xray reports
  297. // per-inbound activity; remote-node snapshots don't carry it, so the service
  298. // layer keys these under the panel's own GUID and a node missing from the
  299. // active-inbounds map means "don't gate" (fall back to the email-only signal).
  300. func (p *Process) GetLocalActiveInbounds() []string {
  301. p.onlineMu.RLock()
  302. defer p.onlineMu.RUnlock()
  303. if len(p.localActiveInbounds) == 0 {
  304. return nil
  305. }
  306. out := make([]string, len(p.localActiveInbounds))
  307. copy(out, p.localActiveInbounds)
  308. return out
  309. }
  310. // RefreshLocalOnline records that each email in activeEmails and each tag in
  311. // activeInboundTags had local xray traffic at now, then rebuilds onlineClients
  312. // and localActiveInbounds from every entry seen within graceMs, pruning older
  313. // ones. Called by the local XrayTrafficJob after each xray gRPC stats poll.
  314. // Pass nil/empty slices to only prune — NodeTrafficSyncJob does this so a
  315. // stopped local xray's clients and inbounds still age out between local polls.
  316. func (p *Process) RefreshLocalOnline(activeEmails, activeInboundTags []string, now, graceMs int64) {
  317. p.onlineMu.Lock()
  318. defer p.onlineMu.Unlock()
  319. if p.localLastOnline == nil {
  320. p.localLastOnline = make(map[string]int64, len(activeEmails))
  321. }
  322. for _, email := range activeEmails {
  323. p.localLastOnline[email] = now
  324. }
  325. online := make([]string, 0, len(p.localLastOnline))
  326. for email, ts := range p.localLastOnline {
  327. if now-ts < graceMs {
  328. online = append(online, email)
  329. } else {
  330. delete(p.localLastOnline, email)
  331. }
  332. }
  333. p.onlineClients = online
  334. if p.localInboundLastActive == nil {
  335. p.localInboundLastActive = make(map[string]int64, len(activeInboundTags))
  336. }
  337. for _, tag := range activeInboundTags {
  338. p.localInboundLastActive[tag] = now
  339. }
  340. activeInbounds := make([]string, 0, len(p.localInboundLastActive))
  341. for tag, ts := range p.localInboundLastActive {
  342. if now-ts < graceMs {
  343. activeInbounds = append(activeInbounds, tag)
  344. } else {
  345. delete(p.localInboundLastActive, tag)
  346. }
  347. }
  348. p.localActiveInbounds = activeInbounds
  349. }
  350. // SetNodeOnlineTree records the GUID-keyed online subtree one direct remote
  351. // node reported (its own clients under its panelGuid plus every descendant
  352. // under theirs). Replaces any previous entry for that node — NodeTrafficSyncJob
  353. // always sends the full subtree per tick.
  354. func (p *Process) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  355. p.onlineMu.Lock()
  356. defer p.onlineMu.Unlock()
  357. if p.nodeOnlineTrees == nil {
  358. p.nodeOnlineTrees = map[int]map[string][]string{}
  359. }
  360. p.nodeOnlineTrees[nodeID] = tree
  361. }
  362. // ClearNodeOnlineClients drops a direct node's whole subtree contribution.
  363. // Called when a probe fails so a downed node — and everything behind it — doesn't
  364. // keep its clients listed as "online" until the next successful probe.
  365. func (p *Process) ClearNodeOnlineClients(nodeID int) {
  366. p.onlineMu.Lock()
  367. defer p.onlineMu.Unlock()
  368. delete(p.nodeOnlineTrees, nodeID)
  369. }
  370. // GetUptime returns the uptime of the Xray process in seconds.
  371. func (p *Process) GetUptime() uint64 {
  372. return uint64(time.Since(p.startTime).Seconds())
  373. }
  374. // refreshAPIPort updates the API port from the inbound configs.
  375. func (p *process) refreshAPIPort() {
  376. for _, inbound := range p.config.InboundConfigs {
  377. if inbound.Tag == "api" {
  378. p.apiPort = inbound.Port
  379. break
  380. }
  381. }
  382. }
  383. // refreshVersion updates the version string by running the Xray binary with -version.
  384. func (p *process) refreshVersion() {
  385. cmd := exec.Command(GetBinaryPath(), "-version")
  386. data, err := cmd.Output()
  387. if err != nil {
  388. p.version = "Unknown"
  389. } else {
  390. datas := bytes.Split(data, []byte(" "))
  391. if len(datas) <= 1 {
  392. p.version = "Unknown"
  393. } else {
  394. p.version = string(datas[1])
  395. }
  396. }
  397. }
  398. // Start launches the Xray process with the current configuration.
  399. func (p *process) Start() (err error) {
  400. if p.IsRunning() {
  401. return errors.New("xray is already running")
  402. }
  403. defer func() {
  404. if err != nil {
  405. logger.Error("Failure in running xray-core process: ", err)
  406. p.exitErr = err
  407. }
  408. }()
  409. data, err := json.MarshalIndent(p.config, "", " ")
  410. if err != nil {
  411. return common.NewErrorf("Failed to generate XRAY configuration files: %v", err)
  412. }
  413. err = os.MkdirAll(config.GetLogFolder(), 0o770)
  414. if err != nil {
  415. logger.Warningf("Failed to create log folder: %s", err)
  416. }
  417. configPath := GetConfigPath()
  418. if p.configPath != "" {
  419. configPath = p.configPath
  420. }
  421. err = os.WriteFile(configPath, data, 0644)
  422. if err != nil {
  423. return common.NewErrorf("Failed to write configuration file: %v", err)
  424. }
  425. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  426. cmd.Stdout = p.logWriter
  427. cmd.Stderr = p.logWriter
  428. err = p.startCommand(cmd)
  429. if err != nil {
  430. return err
  431. }
  432. p.refreshVersion()
  433. p.refreshAPIPort()
  434. return nil
  435. }
  436. func (p *process) startCommand(cmd *exec.Cmd) error {
  437. p.cmd = cmd
  438. p.done = make(chan struct{})
  439. p.exitErr = nil
  440. p.intentionalStop.Store(false)
  441. if err := cmd.Start(); err != nil {
  442. close(p.done)
  443. p.cmd = nil
  444. return err
  445. }
  446. attachChildLifetime(cmd)
  447. go p.waitForCommand(cmd)
  448. return nil
  449. }
  450. func (p *process) waitForCommand(cmd *exec.Cmd) {
  451. defer close(p.done)
  452. err := cmd.Wait()
  453. if err == nil || p.intentionalStop.Load() {
  454. return
  455. }
  456. // On Windows, killing the process results in "exit status 1" which isn't an error for us.
  457. if runtime.GOOS == "windows" {
  458. errStr := strings.ToLower(err.Error())
  459. if strings.Contains(errStr, "exit status 1") {
  460. p.exitErr = err
  461. return
  462. }
  463. }
  464. logger.Error("Failure in running xray-core:", err)
  465. p.exitErr = err
  466. }
  467. // Stop terminates the running Xray process.
  468. func (p *process) Stop() error {
  469. if !p.IsRunning() {
  470. return errors.New("xray is not running")
  471. }
  472. p.intentionalStop.Store(true)
  473. // Remove temporary config file used for test runs so main config is never touched
  474. if p.configPath != "" {
  475. if p.configPath != GetConfigPath() {
  476. // Check if file exists before removing
  477. if _, err := os.Stat(p.configPath); err == nil {
  478. _ = os.Remove(p.configPath)
  479. }
  480. }
  481. }
  482. if runtime.GOOS == "windows" {
  483. if err := p.cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  484. return err
  485. }
  486. return p.waitForExit(xrayForceStopTimeout)
  487. }
  488. if err := p.cmd.Process.Signal(syscall.SIGTERM); err != nil {
  489. if errors.Is(err, os.ErrProcessDone) {
  490. return p.waitForExit(xrayForceStopTimeout)
  491. }
  492. return err
  493. }
  494. if err := p.waitForExit(xrayGracefulStopTimeout); err == nil {
  495. return nil
  496. }
  497. logger.Warning("xray-core did not stop after SIGTERM, killing process")
  498. if err := p.cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  499. return err
  500. }
  501. return p.waitForExit(xrayForceStopTimeout)
  502. }
  503. func (p *process) waitForExit(timeout time.Duration) error {
  504. if p.done == nil {
  505. return nil
  506. }
  507. timer := time.NewTimer(timeout)
  508. defer timer.Stop()
  509. select {
  510. case <-p.done:
  511. return nil
  512. case <-timer.C:
  513. return common.NewErrorf("timed out waiting for xray-core process to stop after %s", timeout)
  514. }
  515. }
  516. const (
  517. crashReportPrefix = "core_crash_"
  518. crashReportSuffix = ".log"
  519. maxCrashReports = 10
  520. )
  521. // writeCrashReport persists a captured xray crash chunk to the log folder
  522. // with nanosecond-precision filename so restart-loop bursts don't overwrite
  523. // each other, and prunes old reports to keep the folder bounded.
  524. func writeCrashReport(m []byte) error {
  525. dir := config.GetLogFolder()
  526. if err := os.MkdirAll(dir, 0o770); err != nil {
  527. return err
  528. }
  529. pruneOldCrashReports(dir, maxCrashReports-1)
  530. name := crashReportPrefix + time.Now().Format("20060102_150405_000000000") + crashReportSuffix
  531. return os.WriteFile(filepath.Join(dir, name), m, 0o640)
  532. }
  533. func pruneOldCrashReports(dir string, keep int) {
  534. entries, err := os.ReadDir(dir)
  535. if err != nil {
  536. return
  537. }
  538. var reports []string
  539. for _, e := range entries {
  540. n := e.Name()
  541. if !e.IsDir() && strings.HasPrefix(n, crashReportPrefix) && strings.HasSuffix(n, crashReportSuffix) {
  542. reports = append(reports, n)
  543. }
  544. }
  545. if len(reports) <= keep {
  546. return
  547. }
  548. sort.Strings(reports)
  549. for _, old := range reports[:len(reports)-keep] {
  550. _ = os.Remove(filepath.Join(dir, old))
  551. }
  552. }