1
0

process.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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. arch := runtime.GOARCH
  24. if arch == "arm" {
  25. arch = "arm32"
  26. }
  27. return fmt.Sprintf("xray-%s-%s", runtime.GOOS, arch)
  28. }
  29. // GetBinaryPath returns the full path to the Xray binary executable.
  30. func GetBinaryPath() string {
  31. return config.GetBinFolderPath() + "/" + GetBinaryName()
  32. }
  33. // GetConfigPath returns the path to the Xray configuration file in the binary folder.
  34. func GetConfigPath() string {
  35. return config.GetBinFolderPath() + "/config.json"
  36. }
  37. // GetGeositePath returns the path to the geosite data file used by Xray.
  38. func GetGeositePath() string {
  39. return config.GetBinFolderPath() + "/geosite.dat"
  40. }
  41. // GetGeoipPath returns the path to the geoip data file used by Xray.
  42. func GetGeoipPath() string {
  43. return config.GetBinFolderPath() + "/geoip.dat"
  44. }
  45. // GetIPLimitLogPath returns the path to the IP limit log file.
  46. func GetIPLimitLogPath() string {
  47. return config.GetLogFolder() + "/3xipl.log"
  48. }
  49. // GetIPLimitBannedLogPath returns the path to the banned IP log file.
  50. func GetIPLimitBannedLogPath() string {
  51. return config.GetLogFolder() + "/3xipl-banned.log"
  52. }
  53. // GetIPLimitBannedPrevLogPath returns the path to the previous banned IP log file.
  54. func GetIPLimitBannedPrevLogPath() string {
  55. return config.GetLogFolder() + "/3xipl-banned.prev.log"
  56. }
  57. // GetAccessPersistentLogPath returns the path to the persistent access log file.
  58. func GetAccessPersistentLogPath() string {
  59. return config.GetLogFolder() + "/3xipl-ap.log"
  60. }
  61. // GetAccessPersistentPrevLogPath returns the path to the previous persistent access log file.
  62. func GetAccessPersistentPrevLogPath() string {
  63. return config.GetLogFolder() + "/3xipl-ap.prev.log"
  64. }
  65. // GetAccessLogPath reads the Xray config and returns the access log file path.
  66. func GetAccessLogPath() (string, error) {
  67. config, err := os.ReadFile(GetConfigPath())
  68. if err != nil {
  69. logger.Warningf("Failed to read configuration file: %s", err)
  70. return "", err
  71. }
  72. jsonConfig := map[string]any{}
  73. err = json.Unmarshal([]byte(config), &jsonConfig)
  74. if err != nil {
  75. logger.Warningf("Failed to parse JSON configuration: %s", err)
  76. return "", err
  77. }
  78. if jsonConfig["log"] != nil {
  79. jsonLog := jsonConfig["log"].(map[string]any)
  80. if jsonLog["access"] != nil {
  81. accessLogPath := jsonLog["access"].(string)
  82. return accessLogPath, nil
  83. }
  84. }
  85. return "", err
  86. }
  87. // stopProcess calls Stop on the given Process instance.
  88. func stopProcess(p *Process) {
  89. p.Stop()
  90. }
  91. // Process wraps an Xray process instance and provides management methods.
  92. type Process struct {
  93. *process
  94. }
  95. // NewProcess creates a new Xray process and sets up cleanup on garbage collection.
  96. func NewProcess(xrayConfig *Config) *Process {
  97. p := &Process{newProcess(xrayConfig)}
  98. runtime.SetFinalizer(p, stopProcess)
  99. return p
  100. }
  101. // NewTestProcess creates a new Xray process that uses a specific config file path.
  102. // Used for test runs (e.g. outbound test) so the main config.json is not overwritten.
  103. // The config file at configPath is removed when the process is stopped.
  104. func NewTestProcess(xrayConfig *Config, configPath string) *Process {
  105. p := &Process{newTestProcess(xrayConfig, configPath)}
  106. runtime.SetFinalizer(p, stopProcess)
  107. return p
  108. }
  109. type process struct {
  110. cmd *exec.Cmd
  111. done chan struct{}
  112. version string
  113. apiPort int
  114. // onlineClients is the set of emails active on THIS panel's own xray
  115. // within the online grace window. It is derived only from local xray
  116. // traffic polls (see RefreshLocalOnline) — never from remote-node
  117. // snapshots — so a client connected solely to a remote node is not
  118. // reported online on local inbounds.
  119. onlineClients []string
  120. // localActiveInbounds is the set of THIS panel's inbound tags that
  121. // carried traffic within the same grace window. Xray's user>>>email
  122. // stat aggregates across every inbound a client is attached to, so an
  123. // online email alone can't say which inbound it actually used. Pairing
  124. // it with the inbound>>>tag stat lets the per-inbound view drop a
  125. // multi-inbound client from inbounds that saw no traffic this window.
  126. localActiveInbounds []string
  127. // localLastOnline records, per email, the last time this panel's own
  128. // xray reported traffic for it. RefreshLocalOnline rebuilds
  129. // onlineClients from this map each tick, keeping the local online set
  130. // independent of the shared client_traffics.last_online column — that
  131. // column is bumped by remote-node syncs too and would otherwise leak
  132. // remote-only clients into the local set.
  133. localLastOnline map[string]int64
  134. // localInboundLastActive mirrors localLastOnline for inbound tags: the
  135. // last tick this panel's xray reported traffic through each tag.
  136. // Rebuilt into localActiveInbounds under the same grace window so the
  137. // two signals stay aligned — an email within grace always has the
  138. // inbound it used within grace too.
  139. localInboundLastActive map[string]int64
  140. // nodeOnlineTrees holds, per direct remote node (keyed by that node's
  141. // panel-local id), the GUID-keyed online-emails subtree that node
  142. // reported — its own clients under its panelGuid plus every descendant
  143. // under theirs. Keying the stored value by GUID (not node id) lets the
  144. // master attribute a deeply nested client to the node that physically
  145. // hosts it across a chain (#4983); the outer node-id key is only so a
  146. // failed probe can drop that whole branch's contribution. NodeTrafficSyncJob
  147. // populates entries per cron tick and clears them when a probe fails. The
  148. // mutex guards this map, onlineClients, and localLastOnline above so the
  149. // online getters never see a torn read.
  150. nodeOnlineTrees map[int]map[string][]string
  151. onlineMu sync.RWMutex
  152. config *Config
  153. configPath string // if set, use this path instead of GetConfigPath() and remove on Stop
  154. logWriter *LogWriter
  155. exitErr error
  156. startTime time.Time
  157. intentionalStop atomic.Bool
  158. }
  159. var (
  160. xrayGracefulStopTimeout = 5 * time.Second
  161. xrayForceStopTimeout = 2 * time.Second
  162. )
  163. // newProcess creates a new internal process struct for Xray.
  164. func newProcess(config *Config) *process {
  165. return &process{
  166. version: "Unknown",
  167. config: config,
  168. logWriter: NewLogWriter(),
  169. startTime: time.Now(),
  170. }
  171. }
  172. // newTestProcess creates a process that writes and runs with a specific config path.
  173. func newTestProcess(config *Config, configPath string) *process {
  174. p := newProcess(config)
  175. p.configPath = configPath
  176. return p
  177. }
  178. // IsRunning returns true if the Xray process is currently running.
  179. func (p *process) IsRunning() bool {
  180. if p.cmd == nil || p.cmd.Process == nil {
  181. return false
  182. }
  183. if p.done != nil {
  184. select {
  185. case <-p.done:
  186. return false
  187. default:
  188. }
  189. }
  190. if p.cmd.ProcessState == nil {
  191. return true
  192. }
  193. return false
  194. }
  195. // GetErr returns the last error encountered by the Xray process.
  196. func (p *process) GetErr() error {
  197. return p.exitErr
  198. }
  199. // GetResult returns the last log line or error from the Xray process.
  200. func (p *process) GetResult() string {
  201. if len(p.logWriter.lastLine) == 0 && p.exitErr != nil {
  202. return p.exitErr.Error()
  203. }
  204. return p.logWriter.lastLine
  205. }
  206. // GetVersion returns the version string of the Xray process.
  207. func (p *process) GetVersion() string {
  208. return p.version
  209. }
  210. // GetAPIPort returns the API port used by the Xray process.
  211. func (p *Process) GetAPIPort() int {
  212. return p.apiPort
  213. }
  214. // GetConfig returns the configuration used by the Xray process.
  215. func (p *Process) GetConfig() *Config {
  216. return p.config
  217. }
  218. // GetOnlineClients returns the union of locally-online clients and
  219. // node-online clients from every registered remote panel. Dedupes by
  220. // email so a client connected to both a local and a node-managed inbound
  221. // surfaces once. Cheap allocation — typical online sets are small and
  222. // the union is recomputed on demand.
  223. func (p *Process) GetOnlineClients() []string {
  224. p.onlineMu.RLock()
  225. defer p.onlineMu.RUnlock()
  226. if len(p.nodeOnlineTrees) == 0 {
  227. // Hot path for single-panel deployments: avoid the map+dedupe
  228. // work entirely and return the local slice as-is.
  229. return p.onlineClients
  230. }
  231. seen := make(map[string]struct{}, len(p.onlineClients))
  232. out := make([]string, 0, len(p.onlineClients))
  233. add := func(emails []string) {
  234. for _, email := range emails {
  235. if _, dup := seen[email]; dup {
  236. continue
  237. }
  238. seen[email] = struct{}{}
  239. out = append(out, email)
  240. }
  241. }
  242. add(p.onlineClients)
  243. for _, tree := range p.nodeOnlineTrees {
  244. for _, emails := range tree {
  245. add(emails)
  246. }
  247. }
  248. return out
  249. }
  250. // GetLocalOnlineClients returns a copy of the emails online on THIS panel's own
  251. // xray within the grace window. The service layer keys these under the panel's
  252. // own GUID when assembling the per-node online view.
  253. func (p *Process) GetLocalOnlineClients() []string {
  254. p.onlineMu.RLock()
  255. defer p.onlineMu.RUnlock()
  256. if len(p.onlineClients) == 0 {
  257. return nil
  258. }
  259. out := make([]string, len(p.onlineClients))
  260. copy(out, p.onlineClients)
  261. return out
  262. }
  263. // GetMergedNodeTrees returns the union of every direct node's reported subtree,
  264. // keyed by the panelGuid of the node that physically hosts each client set.
  265. // Because each child already reports its descendants under their own GUIDs,
  266. // merging the direct children yields the whole tree at any depth (#4983), so a
  267. // client three hops down is attributed to its real node, not the intermediate
  268. // one. GUIDs are globally unique, but a set reported under the same GUID by more
  269. // than one path is deduped per key; empty sets are omitted.
  270. func (p *Process) GetMergedNodeTrees() map[string][]string {
  271. p.onlineMu.RLock()
  272. defer p.onlineMu.RUnlock()
  273. if len(p.nodeOnlineTrees) == 0 {
  274. return map[string][]string{}
  275. }
  276. out := make(map[string][]string)
  277. seen := make(map[string]map[string]struct{})
  278. for _, tree := range p.nodeOnlineTrees {
  279. for guid, emails := range tree {
  280. if guid == "" || len(emails) == 0 {
  281. continue
  282. }
  283. dedup := seen[guid]
  284. if dedup == nil {
  285. dedup = make(map[string]struct{}, len(emails))
  286. seen[guid] = dedup
  287. }
  288. for _, email := range emails {
  289. if _, ok := dedup[email]; ok {
  290. continue
  291. }
  292. dedup[email] = struct{}{}
  293. out[guid] = append(out[guid], email)
  294. }
  295. }
  296. }
  297. return out
  298. }
  299. // GetLocalActiveInbounds returns a copy of THIS panel's inbound tags that
  300. // carried traffic within the grace window. Only the local xray reports
  301. // per-inbound activity; remote-node snapshots don't carry it, so the service
  302. // layer keys these under the panel's own GUID and a node missing from the
  303. // active-inbounds map means "don't gate" (fall back to the email-only signal).
  304. func (p *Process) GetLocalActiveInbounds() []string {
  305. p.onlineMu.RLock()
  306. defer p.onlineMu.RUnlock()
  307. if len(p.localActiveInbounds) == 0 {
  308. return nil
  309. }
  310. out := make([]string, len(p.localActiveInbounds))
  311. copy(out, p.localActiveInbounds)
  312. return out
  313. }
  314. // RefreshLocalOnline records that each email in activeEmails and each tag in
  315. // activeInboundTags had local xray traffic at now, then rebuilds onlineClients
  316. // and localActiveInbounds from every entry seen within graceMs, pruning older
  317. // ones. Called by the local XrayTrafficJob after each xray gRPC stats poll.
  318. // Pass nil/empty slices to only prune — NodeTrafficSyncJob does this so a
  319. // stopped local xray's clients and inbounds still age out between local polls.
  320. func (p *Process) RefreshLocalOnline(activeEmails, activeInboundTags []string, now, graceMs int64) {
  321. p.onlineMu.Lock()
  322. defer p.onlineMu.Unlock()
  323. if p.localLastOnline == nil {
  324. p.localLastOnline = make(map[string]int64, len(activeEmails))
  325. }
  326. for _, email := range activeEmails {
  327. p.localLastOnline[email] = now
  328. }
  329. online := make([]string, 0, len(p.localLastOnline))
  330. for email, ts := range p.localLastOnline {
  331. if now-ts < graceMs {
  332. online = append(online, email)
  333. } else {
  334. delete(p.localLastOnline, email)
  335. }
  336. }
  337. p.onlineClients = online
  338. if p.localInboundLastActive == nil {
  339. p.localInboundLastActive = make(map[string]int64, len(activeInboundTags))
  340. }
  341. for _, tag := range activeInboundTags {
  342. p.localInboundLastActive[tag] = now
  343. }
  344. activeInbounds := make([]string, 0, len(p.localInboundLastActive))
  345. for tag, ts := range p.localInboundLastActive {
  346. if now-ts < graceMs {
  347. activeInbounds = append(activeInbounds, tag)
  348. } else {
  349. delete(p.localInboundLastActive, tag)
  350. }
  351. }
  352. p.localActiveInbounds = activeInbounds
  353. }
  354. // SetNodeOnlineTree records the GUID-keyed online subtree one direct remote
  355. // node reported (its own clients under its panelGuid plus every descendant
  356. // under theirs). Replaces any previous entry for that node — NodeTrafficSyncJob
  357. // always sends the full subtree per tick.
  358. func (p *Process) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  359. p.onlineMu.Lock()
  360. defer p.onlineMu.Unlock()
  361. if p.nodeOnlineTrees == nil {
  362. p.nodeOnlineTrees = map[int]map[string][]string{}
  363. }
  364. p.nodeOnlineTrees[nodeID] = tree
  365. }
  366. // ClearNodeOnlineClients drops a direct node's whole subtree contribution.
  367. // Called when a probe fails so a downed node — and everything behind it — doesn't
  368. // keep its clients listed as "online" until the next successful probe.
  369. func (p *Process) ClearNodeOnlineClients(nodeID int) {
  370. p.onlineMu.Lock()
  371. defer p.onlineMu.Unlock()
  372. delete(p.nodeOnlineTrees, nodeID)
  373. }
  374. // GetUptime returns the uptime of the Xray process in seconds.
  375. func (p *Process) GetUptime() uint64 {
  376. return uint64(time.Since(p.startTime).Seconds())
  377. }
  378. // refreshAPIPort updates the API port from the inbound configs.
  379. func (p *process) refreshAPIPort() {
  380. for _, inbound := range p.config.InboundConfigs {
  381. if inbound.Tag == "api" {
  382. p.apiPort = inbound.Port
  383. break
  384. }
  385. }
  386. }
  387. // refreshVersion updates the version string by running the Xray binary with -version.
  388. func (p *process) refreshVersion() {
  389. cmd := exec.Command(GetBinaryPath(), "-version")
  390. data, err := cmd.Output()
  391. if err != nil {
  392. p.version = "Unknown"
  393. } else {
  394. datas := bytes.Split(data, []byte(" "))
  395. if len(datas) <= 1 {
  396. p.version = "Unknown"
  397. } else {
  398. p.version = string(datas[1])
  399. }
  400. }
  401. }
  402. // Start launches the Xray process with the current configuration.
  403. func (p *process) Start() (err error) {
  404. if p.IsRunning() {
  405. return errors.New("xray is already running")
  406. }
  407. defer func() {
  408. if err != nil {
  409. logger.Error("Failure in running xray-core process: ", err)
  410. p.exitErr = err
  411. }
  412. }()
  413. data, err := json.MarshalIndent(p.config, "", " ")
  414. if err != nil {
  415. return common.NewErrorf("Failed to generate XRAY configuration files: %v", err)
  416. }
  417. err = os.MkdirAll(config.GetLogFolder(), 0o770)
  418. if err != nil {
  419. logger.Warningf("Failed to create log folder: %s", err)
  420. }
  421. configPath := GetConfigPath()
  422. if p.configPath != "" {
  423. configPath = p.configPath
  424. }
  425. err = os.WriteFile(configPath, data, 0644)
  426. if err != nil {
  427. return common.NewErrorf("Failed to write configuration file: %v", err)
  428. }
  429. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  430. cmd.Stdout = p.logWriter
  431. cmd.Stderr = p.logWriter
  432. err = p.startCommand(cmd)
  433. if err != nil {
  434. return err
  435. }
  436. p.refreshVersion()
  437. p.refreshAPIPort()
  438. return nil
  439. }
  440. func (p *process) startCommand(cmd *exec.Cmd) error {
  441. p.cmd = cmd
  442. p.done = make(chan struct{})
  443. p.exitErr = nil
  444. p.intentionalStop.Store(false)
  445. if err := cmd.Start(); err != nil {
  446. close(p.done)
  447. p.cmd = nil
  448. return err
  449. }
  450. attachChildLifetime(cmd)
  451. go p.waitForCommand(cmd)
  452. return nil
  453. }
  454. func (p *process) waitForCommand(cmd *exec.Cmd) {
  455. defer close(p.done)
  456. err := cmd.Wait()
  457. if err == nil || p.intentionalStop.Load() {
  458. return
  459. }
  460. // On Windows, killing the process results in "exit status 1" which isn't an error for us.
  461. if runtime.GOOS == "windows" {
  462. errStr := strings.ToLower(err.Error())
  463. if strings.Contains(errStr, "exit status 1") {
  464. p.exitErr = err
  465. return
  466. }
  467. }
  468. logger.Error("Failure in running xray-core:", err)
  469. p.exitErr = err
  470. }
  471. // Stop terminates the running Xray process.
  472. func (p *process) Stop() error {
  473. if !p.IsRunning() {
  474. return errors.New("xray is not running")
  475. }
  476. p.intentionalStop.Store(true)
  477. // Remove temporary config file used for test runs so main config is never touched
  478. if p.configPath != "" {
  479. if p.configPath != GetConfigPath() {
  480. // Check if file exists before removing
  481. if _, err := os.Stat(p.configPath); err == nil {
  482. _ = os.Remove(p.configPath)
  483. }
  484. }
  485. }
  486. if runtime.GOOS == "windows" {
  487. if err := p.cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  488. return err
  489. }
  490. return p.waitForExit(xrayForceStopTimeout)
  491. }
  492. if err := p.cmd.Process.Signal(syscall.SIGTERM); err != nil {
  493. if errors.Is(err, os.ErrProcessDone) {
  494. return p.waitForExit(xrayForceStopTimeout)
  495. }
  496. return err
  497. }
  498. if err := p.waitForExit(xrayGracefulStopTimeout); err == nil {
  499. return nil
  500. }
  501. logger.Warning("xray-core did not stop after SIGTERM, killing process")
  502. if err := p.cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  503. return err
  504. }
  505. return p.waitForExit(xrayForceStopTimeout)
  506. }
  507. func (p *process) waitForExit(timeout time.Duration) error {
  508. if p.done == nil {
  509. return nil
  510. }
  511. timer := time.NewTimer(timeout)
  512. defer timer.Stop()
  513. select {
  514. case <-p.done:
  515. return nil
  516. case <-timer.C:
  517. return common.NewErrorf("timed out waiting for xray-core process to stop after %s", timeout)
  518. }
  519. }
  520. const (
  521. crashReportPrefix = "core_crash_"
  522. crashReportSuffix = ".log"
  523. maxCrashReports = 10
  524. )
  525. // writeCrashReport persists a captured xray crash chunk to the log folder
  526. // with nanosecond-precision filename so restart-loop bursts don't overwrite
  527. // each other, and prunes old reports to keep the folder bounded.
  528. func writeCrashReport(m []byte) error {
  529. dir := config.GetLogFolder()
  530. if err := os.MkdirAll(dir, 0o770); err != nil {
  531. return err
  532. }
  533. pruneOldCrashReports(dir, maxCrashReports-1)
  534. name := crashReportPrefix + time.Now().Format("20060102_150405_000000000") + crashReportSuffix
  535. return os.WriteFile(filepath.Join(dir, name), m, 0o640)
  536. }
  537. func pruneOldCrashReports(dir string, keep int) {
  538. entries, err := os.ReadDir(dir)
  539. if err != nil {
  540. return
  541. }
  542. var reports []string
  543. for _, e := range entries {
  544. n := e.Name()
  545. if !e.IsDir() && strings.HasPrefix(n, crashReportPrefix) && strings.HasSuffix(n, crashReportSuffix) {
  546. reports = append(reports, n)
  547. }
  548. }
  549. if len(reports) <= keep {
  550. return
  551. }
  552. sort.Strings(reports)
  553. for _, old := range reports[:len(reports)-keep] {
  554. _ = os.Remove(filepath.Join(dir, old))
  555. }
  556. }