process.go 23 KB

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