process.go 22 KB

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