xray.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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. // Wire the panel's own HTTP traffic through the configured outbound, after
  242. // the subscription merge so subscription outbound tags are valid targets.
  243. if egressTag, err := s.settingService.GetPanelOutbound(); err != nil {
  244. logger.Warning("read panelOutbound setting failed:", err)
  245. } else if egressTag != "" {
  246. injectPanelEgress(xrayConfig, egressTag)
  247. }
  248. return xrayConfig, nil
  249. }
  250. // PanelEgressInboundTag is the tag of the loopback SOCKS inbound injected into
  251. // the generated config when a panel outbound is configured. The panel's own
  252. // HTTP clients dial through it to egress via the chosen outbound.
  253. const PanelEgressInboundTag = "panel-egress"
  254. // panelEgressBasePort is the first port tried for the egress bridge; ports
  255. // already taken by other inbounds in the generated config are skipped.
  256. const panelEgressBasePort = 62790
  257. // injectPanelEgress appends a loopback SOCKS inbound to the generated config
  258. // and prepends a routing rule sending it to outboundTag. Both live only in the
  259. // generated config — the stored template is never modified — and both are
  260. // hot-appliable, so changing the panel outbound never restarts the core.
  261. func injectPanelEgress(cfg *xray.Config, outboundTag string) {
  262. for i := range cfg.InboundConfigs {
  263. if cfg.InboundConfigs[i].Tag == PanelEgressInboundTag {
  264. logger.Warning("panel egress: inbound tag [", PanelEgressInboundTag, "] already exists, skipping injection")
  265. return
  266. }
  267. }
  268. // The rule must exist before the inbound takes traffic, otherwise the
  269. // bridge would silently egress through the default outbound instead.
  270. routing := map[string]any{}
  271. if len(cfg.RouterConfig) > 0 {
  272. if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
  273. logger.Warning("panel egress: routing section is unparsable, skipping injection:", err)
  274. return
  275. }
  276. }
  277. rules, _ := routing["rules"].([]any)
  278. rule := map[string]any{
  279. "type": "field",
  280. "inboundTag": []any{PanelEgressInboundTag},
  281. "outboundTag": outboundTag,
  282. }
  283. routing["rules"] = append([]any{rule}, rules...)
  284. newRouting, err := json.Marshal(routing)
  285. if err != nil {
  286. logger.Warning("panel egress: failed to rebuild routing section, skipping injection:", err)
  287. return
  288. }
  289. cfg.RouterConfig = json_util.RawMessage(newRouting)
  290. used := make(map[int]struct{}, len(cfg.InboundConfigs))
  291. for i := range cfg.InboundConfigs {
  292. used[cfg.InboundConfigs[i].Port] = struct{}{}
  293. }
  294. port := panelEgressBasePort
  295. for {
  296. if _, taken := used[port]; !taken {
  297. break
  298. }
  299. port++
  300. }
  301. cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
  302. Listen: json_util.RawMessage(`"127.0.0.1"`),
  303. Port: port,
  304. Protocol: "socks",
  305. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  306. Tag: PanelEgressInboundTag,
  307. })
  308. }
  309. // mergeSubscriptionOutbounds appends the subscription outbounds to the
  310. // OutboundConfigs array of the xray config. It works on the already-unmarshaled
  311. // template so that manually configured outbounds are never overwritten.
  312. //
  313. // Safety: if we cannot parse the template's outbounds array, we leave
  314. // OutboundConfigs exactly as it came from the template (we do not inject
  315. // subscription outbounds). This prevents us from accidentally dropping the
  316. // user's manually configured outbounds when the template is in a weird state.
  317. func mergeSubscriptionOutbounds(cfg *xray.Config, prepend, appendList []any) {
  318. if len(prepend) == 0 && len(appendList) == 0 {
  319. return
  320. }
  321. var templateOutbounds []any
  322. if len(cfg.OutboundConfigs) > 0 {
  323. if err := json.Unmarshal(cfg.OutboundConfigs, &templateOutbounds); err != nil {
  324. // Corrupt template outbounds — do not touch the field at all.
  325. // The user will see problems on Xray start / next save.
  326. return
  327. }
  328. }
  329. merged := make([]any, 0, len(prepend)+len(templateOutbounds)+len(appendList))
  330. merged = append(merged, prepend...)
  331. merged = append(merged, templateOutbounds...)
  332. merged = append(merged, appendList...)
  333. combined, err := json.MarshalIndent(merged, "", " ")
  334. if err != nil {
  335. return
  336. }
  337. cfg.OutboundConfigs = json_util.RawMessage(combined)
  338. }
  339. // ensureAPIServices guarantees the gRPC services the panel depends on are
  340. // listed in the generated config's api block: HandlerService and StatsService
  341. // have always been required for inbound/user management and traffic polling,
  342. // and RoutingService enables hot routing reload on templates saved before it
  343. // was added to the default template. The stored template itself is not
  344. // modified — only the generated runtime config.
  345. func ensureAPIServices(api json_util.RawMessage) json_util.RawMessage {
  346. if len(api) == 0 {
  347. // No api block means the panel's API integration is deliberately
  348. // disabled; don't resurrect it behind the user's back.
  349. return api
  350. }
  351. var parsed map[string]any
  352. if err := json.Unmarshal(api, &parsed); err != nil {
  353. return api
  354. }
  355. services, _ := parsed["services"].([]any)
  356. have := make(map[string]bool, len(services))
  357. for _, svc := range services {
  358. if name, ok := svc.(string); ok {
  359. have[name] = true
  360. }
  361. }
  362. added := false
  363. for _, name := range []string{"HandlerService", "StatsService", "RoutingService"} {
  364. if !have[name] {
  365. services = append(services, name)
  366. added = true
  367. }
  368. }
  369. if !added {
  370. return api
  371. }
  372. parsed["services"] = services
  373. out, err := json.Marshal(parsed)
  374. if err != nil {
  375. return api
  376. }
  377. return out
  378. }
  379. // resolveXrayLogPaths rewrites relative `log.access` / `log.error` values to
  380. // absolute paths under config.GetLogFolder(), so Xray writes those files
  381. // alongside the panel's other logs regardless of the working directory the
  382. // panel was launched from. Values that are empty, "none", or already absolute
  383. // are left untouched, as are unparseable log blocks.
  384. func resolveXrayLogPaths(logCfg json_util.RawMessage) json_util.RawMessage {
  385. if len(logCfg) == 0 {
  386. return logCfg
  387. }
  388. var parsed map[string]any
  389. if err := json.Unmarshal(logCfg, &parsed); err != nil {
  390. return logCfg
  391. }
  392. changed := false
  393. for _, key := range []string{"access", "error"} {
  394. v, ok := parsed[key].(string)
  395. if !ok {
  396. continue
  397. }
  398. trimmed := strings.TrimSpace(v)
  399. if trimmed == "" || strings.EqualFold(trimmed, "none") {
  400. continue
  401. }
  402. if filepath.IsAbs(trimmed) {
  403. continue
  404. }
  405. cleaned := filepath.ToSlash(filepath.Clean(trimmed))
  406. base := filepath.Base(cleaned)
  407. if base == "" || base == "." || base == string(filepath.Separator) {
  408. continue
  409. }
  410. // Only rewrite bare names ("./access.log", "access.log").
  411. // A nested relative path like "./logs/foo.log" is treated as
  412. // a deliberate user choice and left alone.
  413. if cleaned != base {
  414. continue
  415. }
  416. parsed[key] = filepath.Join(config.GetLogFolder(), base)
  417. changed = true
  418. }
  419. if !changed {
  420. return logCfg
  421. }
  422. out, err := json.Marshal(parsed)
  423. if err != nil {
  424. return logCfg
  425. }
  426. return out
  427. }
  428. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  429. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  430. if !s.IsXrayRunning() {
  431. err := errors.New("xray is not running")
  432. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  433. return nil, nil, err
  434. }
  435. apiPort := p.GetAPIPort()
  436. if err := s.xrayAPI.Init(apiPort); err != nil {
  437. logger.Debug("Failed to initialize Xray API:", err)
  438. return nil, nil, err
  439. }
  440. defer s.xrayAPI.Close()
  441. traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
  442. if err != nil {
  443. logger.Debug("Failed to fetch Xray traffic:", err)
  444. return nil, nil, err
  445. }
  446. return traffic, clientTraffic, nil
  447. }
  448. // BalancerStatus is the live view of one balancer for the panel UI. Running
  449. // is false when the balancer isn't present in the running core (e.g. xray is
  450. // stopped or the balancer hasn't been saved/applied yet).
  451. type BalancerStatus struct {
  452. Tag string `json:"tag"`
  453. Running bool `json:"running"`
  454. Override string `json:"override"`
  455. Selected []string `json:"selected"`
  456. }
  457. // GetBalancersStatus queries the running core for the live state of the
  458. // given balancer tags. Per-tag failures are reported as Running=false rather
  459. // than failing the whole call, so the UI can render saved-but-not-applied
  460. // balancers alongside live ones.
  461. func (s *XrayService) GetBalancersStatus(tags []string) ([]BalancerStatus, error) {
  462. statuses := make([]BalancerStatus, 0, len(tags))
  463. if !s.IsXrayRunning() {
  464. for _, tag := range tags {
  465. statuses = append(statuses, BalancerStatus{Tag: tag})
  466. }
  467. return statuses, nil
  468. }
  469. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  470. return nil, err
  471. }
  472. defer s.xrayAPI.Close()
  473. for _, tag := range tags {
  474. info, err := s.xrayAPI.GetBalancerInfo(tag)
  475. if err != nil {
  476. logger.Debug("get balancer info [", tag, "] failed:", err)
  477. statuses = append(statuses, BalancerStatus{Tag: tag})
  478. continue
  479. }
  480. statuses = append(statuses, BalancerStatus{
  481. Tag: tag,
  482. Running: true,
  483. Override: info.Override,
  484. Selected: info.Selected,
  485. })
  486. }
  487. return statuses, nil
  488. }
  489. // OverrideBalancer forces a balancer in the running core to use the given
  490. // outbound tag; an empty target clears the override.
  491. func (s *XrayService) OverrideBalancer(tag, target string) error {
  492. if !s.IsXrayRunning() {
  493. return errors.New("xray is not running")
  494. }
  495. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  496. return err
  497. }
  498. defer s.xrayAPI.Close()
  499. return s.xrayAPI.SetBalancerTarget(tag, target)
  500. }
  501. // TestRoute asks the running core which outbound its router picks for the
  502. // described connection.
  503. func (s *XrayService) TestRoute(req xray.RouteTestRequest) (*xray.RouteTestResult, error) {
  504. if !s.IsXrayRunning() {
  505. return nil, errors.New("xray is not running")
  506. }
  507. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  508. return nil, err
  509. }
  510. defer s.xrayAPI.Close()
  511. return s.xrayAPI.TestRoute(req)
  512. }
  513. // RestartXray reconciles the running Xray process with the current desired
  514. // config. When isForce is false it first tries to apply the changes through
  515. // the Xray gRPC API without restarting the process (inbounds, outbounds and
  516. // routing rules/balancers are hot-reloadable); only changes the core cannot
  517. // take at runtime — or a force request — stop and restart the process.
  518. func (s *XrayService) RestartXray(isForce bool) error {
  519. lock.Lock()
  520. defer lock.Unlock()
  521. logger.Debug("restart Xray, force:", isForce)
  522. isManuallyStopped.Store(false)
  523. xrayConfig, err := s.GetXrayConfig()
  524. if err != nil {
  525. return err
  526. }
  527. if s.IsXrayRunning() {
  528. configUnchanged := p.GetConfig().Equals(xrayConfig)
  529. if !isForce && configUnchanged && !isNeedXrayRestart.Load() {
  530. logger.Debug("It does not need to restart Xray")
  531. return nil
  532. }
  533. if !isForce && !configUnchanged && s.tryHotApply(xrayConfig) {
  534. logger.Info("Xray config changes applied through the core API, no restart needed")
  535. return nil
  536. }
  537. p.Stop()
  538. }
  539. p = xray.NewProcess(xrayConfig)
  540. result = ""
  541. s.xrayAPI.StatsLastValues = nil
  542. err = p.Start()
  543. if err != nil {
  544. return err
  545. }
  546. return nil
  547. }
  548. // tryHotApply attempts to reconcile the running Xray instance with newCfg
  549. // through the core gRPC API (HandlerService for inbounds/outbounds,
  550. // RoutingService for rules/balancers). It returns true when the running
  551. // instance now matches newCfg; on any failure it returns false and the
  552. // caller falls back to a full process restart, which cleans up whatever was
  553. // partially applied. Callers must hold the package-level lock.
  554. func (s *XrayService) tryHotApply(newCfg *xray.Config) bool {
  555. oldCfg := p.GetConfig()
  556. diff, ok := xray.ComputeHotDiff(oldCfg, newCfg)
  557. if !ok {
  558. logger.Debug("hot apply: config change is not API-applicable, falling back to restart")
  559. return false
  560. }
  561. if diff.Empty() {
  562. p.SetConfig(newCfg)
  563. return true
  564. }
  565. apiPort := p.GetAPIPort()
  566. if apiPort <= 0 {
  567. return false
  568. }
  569. // A dedicated client: s.xrayAPI may be in use by traffic polling on other
  570. // service instances and is reset around restarts.
  571. hotAPI := xray.XrayAPI{}
  572. if err := hotAPI.Init(apiPort); err != nil {
  573. logger.Debug("hot apply: failed to init xray api:", err)
  574. return false
  575. }
  576. defer hotAPI.Close()
  577. // Removals first so changed handlers and port swaps never collide with
  578. // the additions that follow.
  579. for _, tag := range diff.RemovedInboundTags {
  580. if err := hotAPI.DelInbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  581. logger.Info("hot apply: remove inbound [", tag, "] failed:", err)
  582. return false
  583. }
  584. }
  585. for _, tag := range diff.RemovedOutboundTags {
  586. if err := hotAPI.DelOutbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  587. logger.Info("hot apply: remove outbound [", tag, "] failed:", err)
  588. return false
  589. }
  590. }
  591. for _, ob := range diff.AddedOutbounds {
  592. if err := addOutboundReconciling(&hotAPI, ob); err != nil {
  593. logger.Info("hot apply: add outbound failed:", err)
  594. return false
  595. }
  596. }
  597. for _, ib := range diff.AddedInbounds {
  598. if err := addInboundReconciling(&hotAPI, ib); err != nil {
  599. logger.Info("hot apply: add inbound failed:", err)
  600. return false
  601. }
  602. }
  603. if diff.RoutingConfig != nil {
  604. if err := hotAPI.ApplyRoutingConfig(diff.RoutingConfig); err != nil {
  605. logger.Info("hot apply: apply routing config failed:", err)
  606. return false
  607. }
  608. }
  609. p.SetConfig(newCfg)
  610. return true
  611. }
  612. // addInboundReconciling adds an inbound, and on a tag conflict (the handler
  613. // was already created through the runtime API while the stored snapshot was
  614. // stale) replaces the existing handler instead.
  615. func addInboundReconciling(api *xray.XrayAPI, inbound []byte) error {
  616. err := api.AddInbound(inbound)
  617. if err == nil || !xray.IsExistingTagErr(err) {
  618. return err
  619. }
  620. var meta struct {
  621. Tag string `json:"tag"`
  622. }
  623. if jsonErr := json.Unmarshal(inbound, &meta); jsonErr != nil || meta.Tag == "" {
  624. return err
  625. }
  626. if delErr := api.DelInbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  627. return delErr
  628. }
  629. return api.AddInbound(inbound)
  630. }
  631. // addOutboundReconciling mirrors addInboundReconciling for outbounds.
  632. func addOutboundReconciling(api *xray.XrayAPI, outbound []byte) error {
  633. err := api.AddOutbound(outbound)
  634. if err == nil || !xray.IsExistingTagErr(err) {
  635. return err
  636. }
  637. var meta struct {
  638. Tag string `json:"tag"`
  639. }
  640. if jsonErr := json.Unmarshal(outbound, &meta); jsonErr != nil || meta.Tag == "" {
  641. return err
  642. }
  643. if delErr := api.DelOutbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  644. return delErr
  645. }
  646. return api.AddOutbound(outbound)
  647. }
  648. // StopXray stops the running Xray process.
  649. func (s *XrayService) StopXray() error {
  650. lock.Lock()
  651. defer lock.Unlock()
  652. isManuallyStopped.Store(true)
  653. logger.Debug("Attempting to stop Xray...")
  654. if s.IsXrayRunning() {
  655. return p.Stop()
  656. }
  657. return errors.New("xray is not running")
  658. }
  659. // SetToNeedRestart marks that Xray needs to be restarted.
  660. func (s *XrayService) SetToNeedRestart() {
  661. isNeedXrayRestart.Store(true)
  662. }
  663. // GetXrayAPIPort returns the port the local xray process is listening on
  664. // for its gRPC HandlerService, or 0 when xray isn't currently running.
  665. // Exposed for the runtime package's LocalRuntime adapter — runtime can't
  666. // reach into the package-level `p` directly without a service-package
  667. // import cycle.
  668. func (s *XrayService) GetXrayAPIPort() int {
  669. if p == nil || !p.IsRunning() {
  670. return 0
  671. }
  672. return p.GetAPIPort()
  673. }
  674. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  675. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  676. return isNeedXrayRestart.CompareAndSwap(true, false)
  677. }
  678. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  679. func (s *XrayService) DidXrayCrash() bool {
  680. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  681. }