process.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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. // GetAccessLogPath reads the Xray config and returns the access log file path.
  58. func GetAccessLogPath() (string, error) {
  59. config, err := os.ReadFile(GetConfigPath())
  60. if err != nil {
  61. logger.Warningf("Failed to read configuration file: %s", err)
  62. return "", err
  63. }
  64. jsonConfig := map[string]any{}
  65. err = json.Unmarshal([]byte(config), &jsonConfig)
  66. if err != nil {
  67. logger.Warningf("Failed to parse JSON configuration: %s", err)
  68. return "", err
  69. }
  70. if jsonConfig["log"] != nil {
  71. jsonLog := jsonConfig["log"].(map[string]any)
  72. if jsonLog["access"] != nil {
  73. accessLogPath := jsonLog["access"].(string)
  74. return accessLogPath, nil
  75. }
  76. }
  77. return "", err
  78. }
  79. // stopProcess calls Stop on the given Process instance.
  80. func stopProcess(p *Process) {
  81. p.Stop()
  82. }
  83. // Process wraps an Xray process instance and provides management methods.
  84. type Process struct {
  85. *process
  86. }
  87. // NewProcess creates a new Xray process and sets up cleanup on garbage collection.
  88. func NewProcess(xrayConfig *Config) *Process {
  89. p := &Process{newProcess(xrayConfig)}
  90. runtime.SetFinalizer(p, stopProcess)
  91. return p
  92. }
  93. // NewTestProcess creates a new Xray process that uses a specific config file path.
  94. // Used for test runs (e.g. outbound test) so the main config.json is not overwritten.
  95. // The config file at configPath is removed when the process is stopped.
  96. func NewTestProcess(xrayConfig *Config, configPath string) *Process {
  97. p := &Process{newTestProcess(xrayConfig, configPath)}
  98. runtime.SetFinalizer(p, stopProcess)
  99. return p
  100. }
  101. type process struct {
  102. // mu guards the process lifecycle fields (cmd, done, exitErr) which are
  103. // written by Start/startCommand and the waitForCommand goroutine while being
  104. // read concurrently by IsRunning/GetErr/GetResult/Stop from other goroutines
  105. // (status endpoint, check-xray-running job). Snapshot under the lock, then do
  106. // any blocking syscall (Wait/Signal/Kill) on the local copy without holding it.
  107. mu sync.RWMutex
  108. cmd *exec.Cmd
  109. done chan struct{}
  110. version string
  111. apiPort int
  112. // onlineClients is the set of emails active on THIS panel's own xray
  113. // within the online grace window. It is derived only from local xray
  114. // traffic polls (see RefreshLocalOnline) — never from remote-node
  115. // snapshots — so a client connected solely to a remote node is not
  116. // reported online on local inbounds.
  117. onlineClients []string
  118. // localActiveInbounds is the set of THIS panel's inbound tags that
  119. // carried traffic within the same grace window. Xray's user>>>email
  120. // stat aggregates across every inbound a client is attached to, so an
  121. // online email alone can't say which inbound it actually used. Pairing
  122. // it with the inbound>>>tag stat lets the per-inbound view drop a
  123. // multi-inbound client from inbounds that saw no traffic this window.
  124. localActiveInbounds []string
  125. // localLastOnline records, per email, the last time this panel's own
  126. // xray reported traffic for it. RefreshLocalOnline rebuilds
  127. // onlineClients from this map each tick, keeping the local online set
  128. // independent of the shared client_traffics.last_online column — that
  129. // column is bumped by remote-node syncs too and would otherwise leak
  130. // remote-only clients into the local set.
  131. localLastOnline map[string]int64
  132. // localInboundLastActive mirrors localLastOnline for inbound tags: the
  133. // last tick this panel's xray reported traffic through each tag.
  134. // Rebuilt into localActiveInbounds under the same grace window so the
  135. // two signals stay aligned — an email within grace always has the
  136. // inbound it used within grace too.
  137. localInboundLastActive map[string]int64
  138. // nodeOnlineTrees holds, per direct remote node (keyed by that node's
  139. // panel-local id), the GUID-keyed online-emails subtree that node
  140. // reported — its own clients under its panelGuid plus every descendant
  141. // under theirs. Keying the stored value by GUID (not node id) lets the
  142. // master attribute a deeply nested client to the node that physically
  143. // hosts it across a chain (#4983); the outer node-id key is only so a
  144. // failed probe can drop that whole branch's contribution. NodeTrafficSyncJob
  145. // populates entries per cron tick and clears them when a probe fails. The
  146. // mutex guards this map, onlineClients, and localLastOnline above so the
  147. // online getters never see a torn read.
  148. nodeOnlineTrees map[int]map[string][]string
  149. onlineMu sync.RWMutex
  150. // onlineAPISupport caches whether the running core implements the
  151. // online-stats RPCs (GetUsersStats). A new process is created on every
  152. // restart/version switch, so the flag resets to Unknown and is re-probed
  153. // lazily by the first caller.
  154. onlineAPISupport atomic.Int32
  155. config *Config
  156. configPath string // if set, use this path instead of GetConfigPath() and remove on Stop
  157. logWriter *LogWriter
  158. exitErr error
  159. startTime time.Time
  160. intentionalStop atomic.Bool
  161. }
  162. // OnlineAPISupport describes whether the running Xray core implements the
  163. // online-stats API (statsUserOnline + GetUsersStats).
  164. type OnlineAPISupport int32
  165. const (
  166. // OnlineAPIUnknown means support has not been probed yet for this process.
  167. OnlineAPIUnknown OnlineAPISupport = iota
  168. // OnlineAPISupported means the core answered the online-stats RPC.
  169. OnlineAPISupported
  170. // OnlineAPIUnsupported means the core returned Unimplemented (older binary).
  171. OnlineAPIUnsupported
  172. )
  173. // OnlineAPISupport returns the cached online-stats capability of this process.
  174. func (p *process) OnlineAPISupport() OnlineAPISupport {
  175. return OnlineAPISupport(p.onlineAPISupport.Load())
  176. }
  177. // SetOnlineAPISupport records the probed online-stats capability of this process.
  178. func (p *process) SetOnlineAPISupport(v OnlineAPISupport) {
  179. p.onlineAPISupport.Store(int32(v))
  180. }
  181. var (
  182. xrayGracefulStopTimeout = 5 * time.Second
  183. xrayForceStopTimeout = 2 * time.Second
  184. // OnCrash is called when xray crashes unexpectedly. Set from web layer.
  185. OnCrash func(err error)
  186. )
  187. // newProcess creates a new internal process struct for Xray.
  188. func newProcess(config *Config) *process {
  189. return &process{
  190. version: "Unknown",
  191. config: config,
  192. logWriter: NewLogWriter(),
  193. startTime: time.Now(),
  194. }
  195. }
  196. // newTestProcess creates a process that writes and runs with a specific config path.
  197. func newTestProcess(config *Config, configPath string) *process {
  198. p := newProcess(config)
  199. p.configPath = configPath
  200. return p
  201. }
  202. // IsRunning returns true if the Xray process is currently running.
  203. func (p *process) IsRunning() bool {
  204. p.mu.RLock()
  205. cmd, done := p.cmd, p.done
  206. p.mu.RUnlock()
  207. if cmd == nil || cmd.Process == nil {
  208. return false
  209. }
  210. // done is closed by the waitForCommand goroutine exactly when cmd.Wait
  211. // returns, i.e. when the process has exited; it is the race-free signal here
  212. // (reading cmd.ProcessState would race with that Wait).
  213. if done != nil {
  214. select {
  215. case <-done:
  216. return false
  217. default:
  218. }
  219. }
  220. return true
  221. }
  222. // GetErr returns the last error encountered by the Xray process.
  223. func (p *process) GetErr() error {
  224. p.mu.RLock()
  225. defer p.mu.RUnlock()
  226. return p.exitErr
  227. }
  228. // GetResult returns the last log line or error from the Xray process.
  229. func (p *process) GetResult() string {
  230. p.mu.RLock()
  231. exitErr := p.exitErr
  232. p.mu.RUnlock()
  233. lastLine := p.logWriter.LastLine()
  234. if len(lastLine) == 0 && exitErr != nil {
  235. return exitErr.Error()
  236. }
  237. return lastLine
  238. }
  239. // GetVersion returns the version string of the Xray process.
  240. func (p *process) GetVersion() string {
  241. return p.version
  242. }
  243. // GetAPIPort returns the API port used by the Xray process.
  244. func (p *Process) GetAPIPort() int {
  245. return p.apiPort
  246. }
  247. // GetConfig returns the configuration used by the Xray process.
  248. func (p *Process) GetConfig() *Config {
  249. return p.config
  250. }
  251. // SetConfig replaces the stored configuration snapshot after the running
  252. // process has been reconciled with it through the gRPC API (hot apply), so
  253. // later change detection compares against what is actually running.
  254. func (p *Process) SetConfig(config *Config) {
  255. p.config = config
  256. }
  257. // GetOnlineClients returns the union of locally-online clients and
  258. // node-online clients from every registered remote panel. Dedupes by
  259. // email so a client connected to both a local and a node-managed inbound
  260. // surfaces once. Cheap allocation — typical online sets are small and
  261. // the union is recomputed on demand.
  262. func (p *Process) GetOnlineClients() []string {
  263. p.onlineMu.RLock()
  264. defer p.onlineMu.RUnlock()
  265. if len(p.nodeOnlineTrees) == 0 {
  266. // Hot path for single-panel deployments: avoid the map+dedupe
  267. // work entirely and return the local slice as-is.
  268. return p.onlineClients
  269. }
  270. seen := make(map[string]struct{}, len(p.onlineClients))
  271. out := make([]string, 0, len(p.onlineClients))
  272. add := func(emails []string) {
  273. for _, email := range emails {
  274. if _, dup := seen[email]; dup {
  275. continue
  276. }
  277. seen[email] = struct{}{}
  278. out = append(out, email)
  279. }
  280. }
  281. add(p.onlineClients)
  282. for _, tree := range p.nodeOnlineTrees {
  283. for _, emails := range tree {
  284. add(emails)
  285. }
  286. }
  287. return out
  288. }
  289. // GetLocalOnlineClients returns a copy of the emails online on THIS panel's own
  290. // xray within the grace window. The service layer keys these under the panel's
  291. // own GUID when assembling the per-node online view.
  292. func (p *Process) GetLocalOnlineClients() []string {
  293. p.onlineMu.RLock()
  294. defer p.onlineMu.RUnlock()
  295. if len(p.onlineClients) == 0 {
  296. return nil
  297. }
  298. out := make([]string, len(p.onlineClients))
  299. copy(out, p.onlineClients)
  300. return out
  301. }
  302. // GetMergedNodeTrees returns the union of every direct node's reported subtree,
  303. // keyed by the panelGuid of the node that physically hosts each client set.
  304. // Because each child already reports its descendants under their own GUIDs,
  305. // merging the direct children yields the whole tree at any depth (#4983), so a
  306. // client three hops down is attributed to its real node, not the intermediate
  307. // one. GUIDs are globally unique, but a set reported under the same GUID by more
  308. // than one path is deduped per key; empty sets are omitted.
  309. func (p *Process) GetMergedNodeTrees() map[string][]string {
  310. p.onlineMu.RLock()
  311. defer p.onlineMu.RUnlock()
  312. if len(p.nodeOnlineTrees) == 0 {
  313. return map[string][]string{}
  314. }
  315. out := make(map[string][]string)
  316. seen := make(map[string]map[string]struct{})
  317. for _, tree := range p.nodeOnlineTrees {
  318. for guid, emails := range tree {
  319. if guid == "" || len(emails) == 0 {
  320. continue
  321. }
  322. dedup := seen[guid]
  323. if dedup == nil {
  324. dedup = make(map[string]struct{}, len(emails))
  325. seen[guid] = dedup
  326. }
  327. for _, email := range emails {
  328. if _, ok := dedup[email]; ok {
  329. continue
  330. }
  331. dedup[email] = struct{}{}
  332. out[guid] = append(out[guid], email)
  333. }
  334. }
  335. }
  336. return out
  337. }
  338. // GetLocalActiveInbounds returns a copy of THIS panel's inbound tags that
  339. // carried traffic within the grace window. Only the local xray reports
  340. // per-inbound activity; remote-node snapshots don't carry it, so the service
  341. // layer keys these under the panel's own GUID and a node missing from the
  342. // active-inbounds map means "don't gate" (fall back to the email-only signal).
  343. func (p *Process) GetLocalActiveInbounds() []string {
  344. p.onlineMu.RLock()
  345. defer p.onlineMu.RUnlock()
  346. if len(p.localActiveInbounds) == 0 {
  347. return nil
  348. }
  349. out := make([]string, len(p.localActiveInbounds))
  350. copy(out, p.localActiveInbounds)
  351. return out
  352. }
  353. // RefreshLocalOnline records that each email in activeEmails and each tag in
  354. // activeInboundTags had local xray traffic at now, then rebuilds onlineClients
  355. // and localActiveInbounds from every entry seen within graceMs, pruning older
  356. // ones. Called by the local XrayTrafficJob after each xray gRPC stats poll.
  357. // Pass nil/empty slices to only prune — NodeTrafficSyncJob does this so a
  358. // stopped local xray's clients and inbounds still age out between local polls.
  359. func (p *Process) RefreshLocalOnline(activeEmails, activeInboundTags []string, now, graceMs int64) {
  360. p.onlineMu.Lock()
  361. defer p.onlineMu.Unlock()
  362. if p.localLastOnline == nil {
  363. p.localLastOnline = make(map[string]int64, len(activeEmails))
  364. }
  365. for _, email := range activeEmails {
  366. p.localLastOnline[email] = now
  367. }
  368. online := make([]string, 0, len(p.localLastOnline))
  369. for email, ts := range p.localLastOnline {
  370. if now-ts < graceMs {
  371. online = append(online, email)
  372. } else {
  373. delete(p.localLastOnline, email)
  374. }
  375. }
  376. p.onlineClients = online
  377. if p.localInboundLastActive == nil {
  378. p.localInboundLastActive = make(map[string]int64, len(activeInboundTags))
  379. }
  380. for _, tag := range activeInboundTags {
  381. p.localInboundLastActive[tag] = now
  382. }
  383. activeInbounds := make([]string, 0, len(p.localInboundLastActive))
  384. for tag, ts := range p.localInboundLastActive {
  385. if now-ts < graceMs {
  386. activeInbounds = append(activeInbounds, tag)
  387. } else {
  388. delete(p.localInboundLastActive, tag)
  389. }
  390. }
  391. p.localActiveInbounds = activeInbounds
  392. }
  393. // SetNodeOnlineTree records the GUID-keyed online subtree one direct remote
  394. // node reported (its own clients under its panelGuid plus every descendant
  395. // under theirs). Replaces any previous entry for that node — NodeTrafficSyncJob
  396. // always sends the full subtree per tick.
  397. func (p *Process) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  398. p.onlineMu.Lock()
  399. defer p.onlineMu.Unlock()
  400. if p.nodeOnlineTrees == nil {
  401. p.nodeOnlineTrees = map[int]map[string][]string{}
  402. }
  403. p.nodeOnlineTrees[nodeID] = tree
  404. }
  405. // ClearNodeOnlineClients drops a direct node's whole subtree contribution.
  406. // Called when a probe fails so a downed node — and everything behind it — doesn't
  407. // keep its clients listed as "online" until the next successful probe.
  408. func (p *Process) ClearNodeOnlineClients(nodeID int) {
  409. p.onlineMu.Lock()
  410. defer p.onlineMu.Unlock()
  411. delete(p.nodeOnlineTrees, nodeID)
  412. }
  413. // GetUptime returns the uptime of the Xray process in seconds.
  414. func (p *Process) GetUptime() uint64 {
  415. return uint64(time.Since(p.startTime).Seconds())
  416. }
  417. // refreshAPIPort updates the API port from the inbound configs.
  418. func (p *process) refreshAPIPort() {
  419. for _, inbound := range p.config.InboundConfigs {
  420. if inbound.Tag == "api" {
  421. p.apiPort = inbound.Port
  422. break
  423. }
  424. }
  425. }
  426. // refreshVersion updates the version string by running the Xray binary with -version.
  427. func (p *process) refreshVersion() {
  428. cmd := exec.Command(GetBinaryPath(), "-version")
  429. data, err := cmd.Output()
  430. if err != nil {
  431. p.version = "Unknown"
  432. } else {
  433. datas := bytes.Split(data, []byte(" "))
  434. if len(datas) <= 1 {
  435. p.version = "Unknown"
  436. } else {
  437. p.version = string(datas[1])
  438. }
  439. }
  440. }
  441. // Start launches the Xray process with the current configuration.
  442. func (p *process) Start() (err error) {
  443. if p.IsRunning() {
  444. return errors.New("xray is already running")
  445. }
  446. defer func() {
  447. if err != nil {
  448. logger.Error("Failure in running xray-core process: ", err)
  449. p.setExitErr(err)
  450. }
  451. }()
  452. data, err := json.MarshalIndent(p.config, "", " ")
  453. if err != nil {
  454. return common.NewErrorf("Failed to generate XRAY configuration files: %v", err)
  455. }
  456. err = os.MkdirAll(config.GetLogFolder(), 0o770)
  457. if err != nil {
  458. logger.Warningf("Failed to create log folder: %s", err)
  459. }
  460. configPath := GetConfigPath()
  461. if p.configPath != "" {
  462. configPath = p.configPath
  463. }
  464. err = writeFileAtomic(configPath, data, 0o600)
  465. if err != nil {
  466. return common.NewErrorf("Failed to write configuration file: %v", err)
  467. }
  468. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  469. cmd.Stdout = p.logWriter
  470. cmd.Stderr = p.logWriter
  471. err = p.startCommand(cmd)
  472. if err != nil {
  473. return err
  474. }
  475. p.refreshVersion()
  476. p.refreshAPIPort()
  477. return nil
  478. }
  479. // writeFileAtomic writes data to path via a same-directory temp file that is
  480. // permissioned, synced, and renamed into place, so a crash can never leave a
  481. // partial config; the config holds credentials, hence the 0600 perm. After the
  482. // rename the parent directory is fsynced to persist the directory entry. That
  483. // final step is skipped on Windows, where directory fsync is unsupported and
  484. // os.Rename already uses replace-existing semantics.
  485. func writeFileAtomic(path string, data []byte, perm os.FileMode) (err error) {
  486. dir := filepath.Dir(path)
  487. tmp, err := os.CreateTemp(dir, ".config-*.tmp")
  488. if err != nil {
  489. return err
  490. }
  491. tmpPath := tmp.Name()
  492. defer func() {
  493. _ = tmp.Close()
  494. if err != nil {
  495. _ = os.Remove(tmpPath)
  496. }
  497. }()
  498. if err = tmp.Chmod(perm); err != nil {
  499. return err
  500. }
  501. if _, err = tmp.Write(data); err != nil {
  502. return err
  503. }
  504. if err = tmp.Sync(); err != nil {
  505. return err
  506. }
  507. if err = tmp.Close(); err != nil {
  508. return err
  509. }
  510. if err = renameFile(tmpPath, path); err != nil {
  511. return err
  512. }
  513. if runtime.GOOS == "windows" {
  514. return nil
  515. }
  516. dirHandle, err := os.Open(dir)
  517. if err != nil {
  518. return err
  519. }
  520. err = dirHandle.Sync()
  521. _ = dirHandle.Close()
  522. return err
  523. }
  524. var renameFile = os.Rename
  525. func (p *process) startCommand(cmd *exec.Cmd) error {
  526. p.mu.Lock()
  527. p.cmd = cmd
  528. p.done = make(chan struct{})
  529. p.exitErr = nil
  530. done := p.done
  531. p.mu.Unlock()
  532. p.intentionalStop.Store(false)
  533. if err := cmd.Start(); err != nil {
  534. close(done)
  535. p.mu.Lock()
  536. p.cmd = nil
  537. p.mu.Unlock()
  538. return err
  539. }
  540. attachChildLifetime(cmd)
  541. go p.waitForCommand(cmd, done)
  542. return nil
  543. }
  544. func (p *process) setExitErr(err error) {
  545. p.mu.Lock()
  546. p.exitErr = err
  547. p.mu.Unlock()
  548. }
  549. func (p *process) waitForCommand(cmd *exec.Cmd, done chan struct{}) {
  550. defer close(done)
  551. err := cmd.Wait()
  552. if err == nil || p.intentionalStop.Load() {
  553. return
  554. }
  555. // On Windows, killing the process results in "exit status 1" which isn't an error for us.
  556. if runtime.GOOS == "windows" {
  557. errStr := strings.ToLower(err.Error())
  558. if strings.Contains(errStr, "exit status 1") {
  559. p.setExitErr(err)
  560. return
  561. }
  562. }
  563. logger.Error("Failure in running xray-core:", err)
  564. p.setExitErr(err)
  565. if OnCrash != nil {
  566. OnCrash(err)
  567. }
  568. }
  569. // Stop terminates the running Xray process.
  570. func (p *process) Stop() error {
  571. if !p.IsRunning() {
  572. return errors.New("xray is not running")
  573. }
  574. p.intentionalStop.Store(true)
  575. // Snapshot cmd once, then run the blocking Signal/Kill/Wait on the local copy
  576. // without holding the lock.
  577. p.mu.RLock()
  578. cmd := p.cmd
  579. p.mu.RUnlock()
  580. if cmd == nil || cmd.Process == nil {
  581. return errors.New("xray is not running")
  582. }
  583. // Remove temporary config file used for test runs so main config is never touched
  584. if p.configPath != "" {
  585. if p.configPath != GetConfigPath() {
  586. // Check if file exists before removing
  587. if _, err := os.Stat(p.configPath); err == nil {
  588. _ = os.Remove(p.configPath)
  589. }
  590. }
  591. }
  592. if runtime.GOOS == "windows" {
  593. if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  594. return err
  595. }
  596. return p.waitForExit(xrayForceStopTimeout)
  597. }
  598. if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
  599. if errors.Is(err, os.ErrProcessDone) {
  600. return p.waitForExit(xrayForceStopTimeout)
  601. }
  602. return err
  603. }
  604. if err := p.waitForExit(xrayGracefulStopTimeout); err == nil {
  605. return nil
  606. }
  607. logger.Warning("xray-core did not stop after SIGTERM, killing process")
  608. if err := cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  609. return err
  610. }
  611. return p.waitForExit(xrayForceStopTimeout)
  612. }
  613. func (p *process) waitForExit(timeout time.Duration) error {
  614. p.mu.RLock()
  615. done := p.done
  616. p.mu.RUnlock()
  617. if done == nil {
  618. return nil
  619. }
  620. timer := time.NewTimer(timeout)
  621. defer timer.Stop()
  622. select {
  623. case <-done:
  624. return nil
  625. case <-timer.C:
  626. return common.NewErrorf("timed out waiting for xray-core process to stop after %s", timeout)
  627. }
  628. }
  629. const (
  630. crashReportPrefix = "core_crash_"
  631. crashReportSuffix = ".log"
  632. maxCrashReports = 10
  633. )
  634. // writeCrashReport persists a captured xray crash chunk to the log folder
  635. // with nanosecond-precision filename so restart-loop bursts don't overwrite
  636. // each other, and prunes old reports to keep the folder bounded.
  637. func writeCrashReport(m []byte) error {
  638. dir := config.GetLogFolder()
  639. if err := os.MkdirAll(dir, 0o770); err != nil {
  640. return err
  641. }
  642. pruneOldCrashReports(dir, maxCrashReports-1)
  643. name := crashReportPrefix + time.Now().Format("20060102_150405_000000000") + crashReportSuffix
  644. return os.WriteFile(filepath.Join(dir, name), m, 0o640)
  645. }
  646. func pruneOldCrashReports(dir string, keep int) {
  647. entries, err := os.ReadDir(dir)
  648. if err != nil {
  649. return
  650. }
  651. var reports []string
  652. for _, e := range entries {
  653. n := e.Name()
  654. if !e.IsDir() && strings.HasPrefix(n, crashReportPrefix) && strings.HasSuffix(n, crashReportSuffix) {
  655. reports = append(reports, n)
  656. }
  657. }
  658. if len(reports) <= keep {
  659. return
  660. }
  661. sort.Strings(reports)
  662. for _, old := range reports[:len(reports)-keep] {
  663. _ = os.Remove(filepath.Join(dir, old))
  664. }
  665. }