xray.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "path/filepath"
  6. "runtime"
  7. "strings"
  8. "sync"
  9. "github.com/mhsanaei/3x-ui/v3/internal/config"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  11. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  12. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  13. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  14. "go.uber.org/atomic"
  15. )
  16. var (
  17. p *xray.Process
  18. lock sync.Mutex
  19. isNeedXrayRestart atomic.Bool // Indicates that restart was requested for Xray
  20. isManuallyStopped atomic.Bool // Indicates that Xray was stopped manually from the panel
  21. result string
  22. )
  23. // XrayService provides business logic for Xray process management.
  24. // It handles starting, stopping, restarting Xray, and managing its configuration.
  25. type XrayService struct {
  26. inboundService InboundService
  27. settingService SettingService
  28. xrayAPI xray.XrayAPI
  29. }
  30. // IsXrayRunning checks if the Xray process is currently running.
  31. func (s *XrayService) IsXrayRunning() bool {
  32. return p != nil && p.IsRunning()
  33. }
  34. // XrayProcess returns the current Xray process instance (may be nil when Xray
  35. // is not running). It exposes the package-level process to callers outside this
  36. // package (e.g. the tgbot subpackage) without changing access semantics.
  37. func XrayProcess() *xray.Process {
  38. return p
  39. }
  40. // GetXrayErr returns the error from the Xray process, if any.
  41. func (s *XrayService) GetXrayErr() error {
  42. if p == nil {
  43. return nil
  44. }
  45. err := p.GetErr()
  46. if err == nil {
  47. return nil
  48. }
  49. if runtime.GOOS == "windows" && err.Error() == "exit status 1" {
  50. // exit status 1 on Windows means that Xray process was killed
  51. // as we kill process to stop in on Windows, this is not an error
  52. return nil
  53. }
  54. return err
  55. }
  56. // GetXrayResult returns the result string from the Xray process.
  57. func (s *XrayService) GetXrayResult() string {
  58. if result != "" {
  59. return result
  60. }
  61. if s.IsXrayRunning() {
  62. return ""
  63. }
  64. if p == nil {
  65. return ""
  66. }
  67. result = p.GetResult()
  68. if runtime.GOOS == "windows" && result == "exit status 1" {
  69. // exit status 1 on Windows means that Xray process was killed
  70. // as we kill process to stop in on Windows, this is not an error
  71. return ""
  72. }
  73. return result
  74. }
  75. // GetXrayVersion returns the version of the running Xray process.
  76. func (s *XrayService) GetXrayVersion() string {
  77. if p == nil {
  78. return "Unknown"
  79. }
  80. return p.GetVersion()
  81. }
  82. // RemoveIndex removes an element at the specified index from a slice.
  83. // Returns a new slice with the element removed.
  84. func RemoveIndex(s []any, index int) []any {
  85. return append(s[:index], s[index+1:]...)
  86. }
  87. // GetXrayConfig retrieves and builds the Xray configuration from settings and inbounds.
  88. func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
  89. templateConfig, err := s.settingService.GetXrayConfigTemplate()
  90. if err != nil {
  91. return nil, err
  92. }
  93. xrayConfig := &xray.Config{}
  94. err = json.Unmarshal([]byte(templateConfig), xrayConfig)
  95. if err != nil {
  96. return nil, err
  97. }
  98. xrayConfig.LogConfig = resolveXrayLogPaths(xrayConfig.LogConfig)
  99. xrayConfig.API = ensureAPIServices(xrayConfig.API)
  100. _, _, _ = s.inboundService.AddTraffic(nil, nil)
  101. inbounds, err := s.inboundService.GetAllInbounds()
  102. if err != nil {
  103. return nil, err
  104. }
  105. for _, inbound := range inbounds {
  106. if !inbound.Enable {
  107. continue
  108. }
  109. if inbound.NodeID != nil {
  110. continue
  111. }
  112. if inbound.Protocol == model.MTProto {
  113. continue
  114. }
  115. settings := map[string]any{}
  116. json.Unmarshal([]byte(inbound.Settings), &settings)
  117. dbClients, listErr := s.inboundService.clientService.ListForInbound(nil, inbound.Id)
  118. if listErr != nil {
  119. return nil, listErr
  120. }
  121. clientStats := inbound.ClientStats
  122. enableMap := make(map[string]bool, len(clientStats))
  123. for _, clientTraffic := range clientStats {
  124. enableMap[clientTraffic.Email] = clientTraffic.Enable
  125. }
  126. var finalClients []any
  127. for i := range dbClients {
  128. c := dbClients[i]
  129. if enable, exists := enableMap[c.Email]; exists && !enable {
  130. logger.Infof("Remove Inbound User %s due to expiration or traffic limit", c.Email)
  131. continue
  132. }
  133. if !c.Enable {
  134. continue
  135. }
  136. flow := c.Flow
  137. if flow == "xtls-rprx-vision-udp443" {
  138. flow = "xtls-rprx-vision"
  139. }
  140. entry := map[string]any{"email": c.Email}
  141. switch inbound.Protocol {
  142. case model.VLESS:
  143. if c.ID != "" {
  144. entry["id"] = c.ID
  145. }
  146. if flow != "" {
  147. entry["flow"] = flow
  148. }
  149. if c.Reverse != nil {
  150. entry["reverse"] = c.Reverse
  151. }
  152. case model.VMESS:
  153. if c.ID != "" {
  154. entry["id"] = c.ID
  155. }
  156. if c.Security != "" {
  157. entry["security"] = c.Security
  158. }
  159. case model.Trojan:
  160. if c.Password != "" {
  161. entry["password"] = c.Password
  162. }
  163. if flow != "" {
  164. entry["flow"] = flow
  165. }
  166. case model.Shadowsocks:
  167. if c.Password != "" {
  168. entry["password"] = c.Password
  169. }
  170. case model.Hysteria:
  171. if c.Auth != "" {
  172. entry["auth"] = c.Auth
  173. }
  174. }
  175. finalClients = append(finalClients, entry)
  176. }
  177. _, hadClients := settings["clients"]
  178. mutated := hadClients || len(finalClients) > 0
  179. if mutated {
  180. settings["clients"] = finalClients
  181. }
  182. if inboundCanHostFallbacks(inbound) {
  183. fallbacks, fbErr := s.inboundService.fallbackService.BuildFallbacksJSON(nil, inbound.Id)
  184. if fbErr != nil {
  185. return nil, fbErr
  186. }
  187. if len(fallbacks) > 0 {
  188. generic := make([]any, 0, len(fallbacks))
  189. for _, f := range fallbacks {
  190. generic = append(generic, f)
  191. }
  192. settings["fallbacks"] = generic
  193. mutated = true
  194. }
  195. }
  196. if mutated {
  197. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  198. if err != nil {
  199. return nil, err
  200. }
  201. inbound.Settings = string(modifiedSettings)
  202. }
  203. if len(inbound.StreamSettings) > 0 {
  204. // Unmarshal stream JSON
  205. var stream map[string]any
  206. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  207. // Remove the "settings" field under "tlsSettings" and "realitySettings"
  208. tlsSettings, ok1 := stream["tlsSettings"].(map[string]any)
  209. realitySettings, ok2 := stream["realitySettings"].(map[string]any)
  210. if ok1 || ok2 {
  211. if ok1 {
  212. delete(tlsSettings, "settings")
  213. } else if ok2 {
  214. delete(realitySettings, "settings")
  215. }
  216. }
  217. delete(stream, "externalProxy")
  218. newStream, err := json.MarshalIndent(stream, "", " ")
  219. if err != nil {
  220. return nil, err
  221. }
  222. inbound.StreamSettings = string(newStream)
  223. }
  224. if inbound.Protocol == model.Shadowsocks {
  225. if healed, ok := model.HealShadowsocksClientMethods(inbound.Settings); ok {
  226. inbound.Settings = healed
  227. }
  228. }
  229. inboundConfig := inbound.GenXrayInboundConfig()
  230. xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig)
  231. }
  232. // Merge subscription-derived outbounds (if any) into the final outbounds array.
  233. // These are additive: each subscription is placed before or after the template
  234. // outbounds based on its Prepend flag, ordered by Priority. Tags assigned by the
  235. // subscription service are kept stable across refreshes so that balancers and
  236. // routing rules continue to work.
  237. subSvc := &OutboundSubscriptionService{}
  238. if prepend, appendList, err := subSvc.activeOutboundsSplit(); err == nil && (len(prepend) > 0 || len(appendList) > 0) {
  239. mergeSubscriptionOutbounds(xrayConfig, prepend, appendList)
  240. }
  241. return xrayConfig, nil
  242. }
  243. // mergeSubscriptionOutbounds appends the subscription outbounds to the
  244. // OutboundConfigs array of the xray config. It works on the already-unmarshaled
  245. // template so that manually configured outbounds are never overwritten.
  246. //
  247. // Safety: if we cannot parse the template's outbounds array, we leave
  248. // OutboundConfigs exactly as it came from the template (we do not inject
  249. // subscription outbounds). This prevents us from accidentally dropping the
  250. // user's manually configured outbounds when the template is in a weird state.
  251. func mergeSubscriptionOutbounds(cfg *xray.Config, prepend, appendList []any) {
  252. if len(prepend) == 0 && len(appendList) == 0 {
  253. return
  254. }
  255. var templateOutbounds []any
  256. if len(cfg.OutboundConfigs) > 0 {
  257. if err := json.Unmarshal(cfg.OutboundConfigs, &templateOutbounds); err != nil {
  258. // Corrupt template outbounds — do not touch the field at all.
  259. // The user will see problems on Xray start / next save.
  260. return
  261. }
  262. }
  263. merged := make([]any, 0, len(prepend)+len(templateOutbounds)+len(appendList))
  264. merged = append(merged, prepend...)
  265. merged = append(merged, templateOutbounds...)
  266. merged = append(merged, appendList...)
  267. combined, err := json.MarshalIndent(merged, "", " ")
  268. if err != nil {
  269. return
  270. }
  271. cfg.OutboundConfigs = json_util.RawMessage(combined)
  272. }
  273. // ensureAPIServices guarantees the gRPC services the panel depends on are
  274. // listed in the generated config's api block: HandlerService and StatsService
  275. // have always been required for inbound/user management and traffic polling,
  276. // and RoutingService enables hot routing reload on templates saved before it
  277. // was added to the default template. The stored template itself is not
  278. // modified — only the generated runtime config.
  279. func ensureAPIServices(api json_util.RawMessage) json_util.RawMessage {
  280. if len(api) == 0 {
  281. // No api block means the panel's API integration is deliberately
  282. // disabled; don't resurrect it behind the user's back.
  283. return api
  284. }
  285. var parsed map[string]any
  286. if err := json.Unmarshal(api, &parsed); err != nil {
  287. return api
  288. }
  289. services, _ := parsed["services"].([]any)
  290. have := make(map[string]bool, len(services))
  291. for _, svc := range services {
  292. if name, ok := svc.(string); ok {
  293. have[name] = true
  294. }
  295. }
  296. added := false
  297. for _, name := range []string{"HandlerService", "StatsService", "RoutingService"} {
  298. if !have[name] {
  299. services = append(services, name)
  300. added = true
  301. }
  302. }
  303. if !added {
  304. return api
  305. }
  306. parsed["services"] = services
  307. out, err := json.Marshal(parsed)
  308. if err != nil {
  309. return api
  310. }
  311. return out
  312. }
  313. // resolveXrayLogPaths rewrites relative `log.access` / `log.error` values to
  314. // absolute paths under config.GetLogFolder(), so Xray writes those files
  315. // alongside the panel's other logs regardless of the working directory the
  316. // panel was launched from. Values that are empty, "none", or already absolute
  317. // are left untouched, as are unparseable log blocks.
  318. func resolveXrayLogPaths(logCfg json_util.RawMessage) json_util.RawMessage {
  319. if len(logCfg) == 0 {
  320. return logCfg
  321. }
  322. var parsed map[string]any
  323. if err := json.Unmarshal(logCfg, &parsed); err != nil {
  324. return logCfg
  325. }
  326. changed := false
  327. for _, key := range []string{"access", "error"} {
  328. v, ok := parsed[key].(string)
  329. if !ok {
  330. continue
  331. }
  332. trimmed := strings.TrimSpace(v)
  333. if trimmed == "" || strings.EqualFold(trimmed, "none") {
  334. continue
  335. }
  336. if filepath.IsAbs(trimmed) {
  337. continue
  338. }
  339. cleaned := filepath.ToSlash(filepath.Clean(trimmed))
  340. base := filepath.Base(cleaned)
  341. if base == "" || base == "." || base == string(filepath.Separator) {
  342. continue
  343. }
  344. // Only rewrite bare names ("./access.log", "access.log").
  345. // A nested relative path like "./logs/foo.log" is treated as
  346. // a deliberate user choice and left alone.
  347. if cleaned != base {
  348. continue
  349. }
  350. parsed[key] = filepath.Join(config.GetLogFolder(), base)
  351. changed = true
  352. }
  353. if !changed {
  354. return logCfg
  355. }
  356. out, err := json.Marshal(parsed)
  357. if err != nil {
  358. return logCfg
  359. }
  360. return out
  361. }
  362. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  363. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  364. if !s.IsXrayRunning() {
  365. err := errors.New("xray is not running")
  366. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  367. return nil, nil, err
  368. }
  369. apiPort := p.GetAPIPort()
  370. if err := s.xrayAPI.Init(apiPort); err != nil {
  371. logger.Debug("Failed to initialize Xray API:", err)
  372. return nil, nil, err
  373. }
  374. defer s.xrayAPI.Close()
  375. traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
  376. if err != nil {
  377. logger.Debug("Failed to fetch Xray traffic:", err)
  378. return nil, nil, err
  379. }
  380. return traffic, clientTraffic, nil
  381. }
  382. // BalancerStatus is the live view of one balancer for the panel UI. Running
  383. // is false when the balancer isn't present in the running core (e.g. xray is
  384. // stopped or the balancer hasn't been saved/applied yet).
  385. type BalancerStatus struct {
  386. Tag string `json:"tag"`
  387. Running bool `json:"running"`
  388. Override string `json:"override"`
  389. Selected []string `json:"selected"`
  390. }
  391. // GetBalancersStatus queries the running core for the live state of the
  392. // given balancer tags. Per-tag failures are reported as Running=false rather
  393. // than failing the whole call, so the UI can render saved-but-not-applied
  394. // balancers alongside live ones.
  395. func (s *XrayService) GetBalancersStatus(tags []string) ([]BalancerStatus, error) {
  396. statuses := make([]BalancerStatus, 0, len(tags))
  397. if !s.IsXrayRunning() {
  398. for _, tag := range tags {
  399. statuses = append(statuses, BalancerStatus{Tag: tag})
  400. }
  401. return statuses, nil
  402. }
  403. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  404. return nil, err
  405. }
  406. defer s.xrayAPI.Close()
  407. for _, tag := range tags {
  408. info, err := s.xrayAPI.GetBalancerInfo(tag)
  409. if err != nil {
  410. logger.Debug("get balancer info [", tag, "] failed:", err)
  411. statuses = append(statuses, BalancerStatus{Tag: tag})
  412. continue
  413. }
  414. statuses = append(statuses, BalancerStatus{
  415. Tag: tag,
  416. Running: true,
  417. Override: info.Override,
  418. Selected: info.Selected,
  419. })
  420. }
  421. return statuses, nil
  422. }
  423. // OverrideBalancer forces a balancer in the running core to use the given
  424. // outbound tag; an empty target clears the override.
  425. func (s *XrayService) OverrideBalancer(tag, target string) error {
  426. if !s.IsXrayRunning() {
  427. return errors.New("xray is not running")
  428. }
  429. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  430. return err
  431. }
  432. defer s.xrayAPI.Close()
  433. return s.xrayAPI.SetBalancerTarget(tag, target)
  434. }
  435. // TestRoute asks the running core which outbound its router picks for the
  436. // described connection.
  437. func (s *XrayService) TestRoute(req xray.RouteTestRequest) (*xray.RouteTestResult, error) {
  438. if !s.IsXrayRunning() {
  439. return nil, errors.New("xray is not running")
  440. }
  441. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  442. return nil, err
  443. }
  444. defer s.xrayAPI.Close()
  445. return s.xrayAPI.TestRoute(req)
  446. }
  447. // RestartXray reconciles the running Xray process with the current desired
  448. // config. When isForce is false it first tries to apply the changes through
  449. // the Xray gRPC API without restarting the process (inbounds, outbounds and
  450. // routing rules/balancers are hot-reloadable); only changes the core cannot
  451. // take at runtime — or a force request — stop and restart the process.
  452. func (s *XrayService) RestartXray(isForce bool) error {
  453. lock.Lock()
  454. defer lock.Unlock()
  455. logger.Debug("restart Xray, force:", isForce)
  456. isManuallyStopped.Store(false)
  457. xrayConfig, err := s.GetXrayConfig()
  458. if err != nil {
  459. return err
  460. }
  461. if s.IsXrayRunning() {
  462. configUnchanged := p.GetConfig().Equals(xrayConfig)
  463. if !isForce && configUnchanged && !isNeedXrayRestart.Load() {
  464. logger.Debug("It does not need to restart Xray")
  465. return nil
  466. }
  467. if !isForce && !configUnchanged && s.tryHotApply(xrayConfig) {
  468. logger.Info("Xray config changes applied through the core API, no restart needed")
  469. return nil
  470. }
  471. p.Stop()
  472. }
  473. p = xray.NewProcess(xrayConfig)
  474. result = ""
  475. s.xrayAPI.StatsLastValues = nil
  476. err = p.Start()
  477. if err != nil {
  478. return err
  479. }
  480. return nil
  481. }
  482. // tryHotApply attempts to reconcile the running Xray instance with newCfg
  483. // through the core gRPC API (HandlerService for inbounds/outbounds,
  484. // RoutingService for rules/balancers). It returns true when the running
  485. // instance now matches newCfg; on any failure it returns false and the
  486. // caller falls back to a full process restart, which cleans up whatever was
  487. // partially applied. Callers must hold the package-level lock.
  488. func (s *XrayService) tryHotApply(newCfg *xray.Config) bool {
  489. oldCfg := p.GetConfig()
  490. diff, ok := xray.ComputeHotDiff(oldCfg, newCfg)
  491. if !ok {
  492. logger.Debug("hot apply: config change is not API-applicable, falling back to restart")
  493. return false
  494. }
  495. if diff.Empty() {
  496. p.SetConfig(newCfg)
  497. return true
  498. }
  499. apiPort := p.GetAPIPort()
  500. if apiPort <= 0 {
  501. return false
  502. }
  503. // A dedicated client: s.xrayAPI may be in use by traffic polling on other
  504. // service instances and is reset around restarts.
  505. hotAPI := xray.XrayAPI{}
  506. if err := hotAPI.Init(apiPort); err != nil {
  507. logger.Debug("hot apply: failed to init xray api:", err)
  508. return false
  509. }
  510. defer hotAPI.Close()
  511. // Removals first so changed handlers and port swaps never collide with
  512. // the additions that follow.
  513. for _, tag := range diff.RemovedInboundTags {
  514. if err := hotAPI.DelInbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  515. logger.Info("hot apply: remove inbound [", tag, "] failed:", err)
  516. return false
  517. }
  518. }
  519. for _, tag := range diff.RemovedOutboundTags {
  520. if err := hotAPI.DelOutbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  521. logger.Info("hot apply: remove outbound [", tag, "] failed:", err)
  522. return false
  523. }
  524. }
  525. for _, ob := range diff.AddedOutbounds {
  526. if err := addOutboundReconciling(&hotAPI, ob); err != nil {
  527. logger.Info("hot apply: add outbound failed:", err)
  528. return false
  529. }
  530. }
  531. for _, ib := range diff.AddedInbounds {
  532. if err := addInboundReconciling(&hotAPI, ib); err != nil {
  533. logger.Info("hot apply: add inbound failed:", err)
  534. return false
  535. }
  536. }
  537. if diff.RoutingConfig != nil {
  538. if err := hotAPI.ApplyRoutingConfig(diff.RoutingConfig); err != nil {
  539. logger.Info("hot apply: apply routing config failed:", err)
  540. return false
  541. }
  542. }
  543. p.SetConfig(newCfg)
  544. return true
  545. }
  546. // addInboundReconciling adds an inbound, and on a tag conflict (the handler
  547. // was already created through the runtime API while the stored snapshot was
  548. // stale) replaces the existing handler instead.
  549. func addInboundReconciling(api *xray.XrayAPI, inbound []byte) error {
  550. err := api.AddInbound(inbound)
  551. if err == nil || !xray.IsExistingTagErr(err) {
  552. return err
  553. }
  554. var meta struct {
  555. Tag string `json:"tag"`
  556. }
  557. if jsonErr := json.Unmarshal(inbound, &meta); jsonErr != nil || meta.Tag == "" {
  558. return err
  559. }
  560. if delErr := api.DelInbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  561. return delErr
  562. }
  563. return api.AddInbound(inbound)
  564. }
  565. // addOutboundReconciling mirrors addInboundReconciling for outbounds.
  566. func addOutboundReconciling(api *xray.XrayAPI, outbound []byte) error {
  567. err := api.AddOutbound(outbound)
  568. if err == nil || !xray.IsExistingTagErr(err) {
  569. return err
  570. }
  571. var meta struct {
  572. Tag string `json:"tag"`
  573. }
  574. if jsonErr := json.Unmarshal(outbound, &meta); jsonErr != nil || meta.Tag == "" {
  575. return err
  576. }
  577. if delErr := api.DelOutbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  578. return delErr
  579. }
  580. return api.AddOutbound(outbound)
  581. }
  582. // StopXray stops the running Xray process.
  583. func (s *XrayService) StopXray() error {
  584. lock.Lock()
  585. defer lock.Unlock()
  586. isManuallyStopped.Store(true)
  587. logger.Debug("Attempting to stop Xray...")
  588. if s.IsXrayRunning() {
  589. return p.Stop()
  590. }
  591. return errors.New("xray is not running")
  592. }
  593. // SetToNeedRestart marks that Xray needs to be restarted.
  594. func (s *XrayService) SetToNeedRestart() {
  595. isNeedXrayRestart.Store(true)
  596. }
  597. // GetXrayAPIPort returns the port the local xray process is listening on
  598. // for its gRPC HandlerService, or 0 when xray isn't currently running.
  599. // Exposed for the runtime package's LocalRuntime adapter — runtime can't
  600. // reach into the package-level `p` directly without a service-package
  601. // import cycle.
  602. func (s *XrayService) GetXrayAPIPort() int {
  603. if p == nil || !p.IsRunning() {
  604. return 0
  605. }
  606. return p.GetAPIPort()
  607. }
  608. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  609. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  610. return isNeedXrayRestart.CompareAndSwap(true, false)
  611. }
  612. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  613. func (s *XrayService) DidXrayCrash() bool {
  614. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  615. }