process.go 25 KB

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