1
0

process.go 19 KB

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