xray.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "path"
  6. "path/filepath"
  7. "runtime"
  8. "strings"
  9. "sync"
  10. "github.com/mhsanaei/3x-ui/v3/internal/config"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  13. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  14. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  15. "go.uber.org/atomic"
  16. )
  17. var (
  18. p *xray.Process
  19. lock sync.Mutex
  20. isNeedXrayRestart atomic.Bool // Indicates that restart was requested for Xray
  21. isManuallyStopped atomic.Bool // Indicates that Xray was stopped manually from the panel
  22. result string
  23. )
  24. // XrayService provides business logic for Xray process management.
  25. // It handles starting, stopping, restarting Xray, and managing its configuration.
  26. type XrayService struct {
  27. inboundService InboundService
  28. settingService SettingService
  29. xrayAPI xray.XrayAPI
  30. }
  31. // IsXrayRunning checks if the Xray process is currently running.
  32. func (s *XrayService) IsXrayRunning() bool {
  33. return p != nil && p.IsRunning()
  34. }
  35. // XrayProcess returns the current Xray process instance (may be nil when Xray
  36. // is not running). It exposes the package-level process to callers outside this
  37. // package (e.g. the tgbot subpackage) without changing access semantics.
  38. func XrayProcess() *xray.Process {
  39. return p
  40. }
  41. // GetXrayErr returns the error from the Xray process, if any.
  42. func (s *XrayService) GetXrayErr() error {
  43. if p == nil {
  44. return nil
  45. }
  46. err := p.GetErr()
  47. if err == nil {
  48. return nil
  49. }
  50. if runtime.GOOS == "windows" && err.Error() == "exit status 1" {
  51. // exit status 1 on Windows means that Xray process was killed
  52. // as we kill process to stop in on Windows, this is not an error
  53. return nil
  54. }
  55. return err
  56. }
  57. // GetXrayResult returns the result string from the Xray process.
  58. func (s *XrayService) GetXrayResult() string {
  59. if result != "" {
  60. return result
  61. }
  62. if s.IsXrayRunning() {
  63. return ""
  64. }
  65. if p == nil {
  66. return ""
  67. }
  68. result = p.GetResult()
  69. if runtime.GOOS == "windows" && result == "exit status 1" {
  70. // exit status 1 on Windows means that Xray process was killed
  71. // as we kill process to stop in on Windows, this is not an error
  72. return ""
  73. }
  74. return result
  75. }
  76. // GetXrayVersion returns the version of the running Xray process.
  77. func (s *XrayService) GetXrayVersion() string {
  78. if p == nil {
  79. return "Unknown"
  80. }
  81. return p.GetVersion()
  82. }
  83. // RemoveIndex removes an element at the specified index from a slice.
  84. // Returns a new slice with the element removed.
  85. func RemoveIndex(s []any, index int) []any {
  86. return append(s[:index], s[index+1:]...)
  87. }
  88. // GetXrayConfig retrieves and builds the Xray configuration from settings and inbounds.
  89. func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
  90. templateConfig, err := s.settingService.GetXrayConfigTemplate()
  91. if err != nil {
  92. return nil, err
  93. }
  94. xrayConfig := &xray.Config{}
  95. err = json.Unmarshal([]byte(templateConfig), xrayConfig)
  96. if err != nil {
  97. return nil, err
  98. }
  99. xrayConfig.LogConfig = resolveXrayLogPaths(xrayConfig.LogConfig)
  100. xrayConfig.API = ensureAPIServices(xrayConfig.API)
  101. xrayConfig.Policy = ensureStatsPolicy(xrayConfig.Policy)
  102. _, _, _ = s.inboundService.AddTraffic(nil, nil)
  103. inbounds, err := s.inboundService.GetAllInbounds()
  104. if err != nil {
  105. return nil, err
  106. }
  107. for _, inbound := range inbounds {
  108. if !inbound.Enable {
  109. continue
  110. }
  111. if inbound.NodeID != nil {
  112. continue
  113. }
  114. if inbound.Protocol == model.MTProto {
  115. continue
  116. }
  117. settings := map[string]any{}
  118. json.Unmarshal([]byte(inbound.Settings), &settings)
  119. dbClients, listErr := s.inboundService.clientService.ListForInbound(nil, inbound.Id)
  120. if listErr != nil {
  121. return nil, listErr
  122. }
  123. clientStats := inbound.ClientStats
  124. enableMap := make(map[string]bool, len(clientStats))
  125. for _, clientTraffic := range clientStats {
  126. enableMap[clientTraffic.Email] = clientTraffic.Enable
  127. }
  128. var finalClients []any
  129. for i := range dbClients {
  130. c := dbClients[i]
  131. if enable, exists := enableMap[c.Email]; exists && !enable {
  132. logger.Infof("Remove Inbound User %s due to expiration or traffic limit", c.Email)
  133. continue
  134. }
  135. if !c.Enable {
  136. continue
  137. }
  138. flow := c.Flow
  139. if flow == "xtls-rprx-vision-udp443" {
  140. flow = "xtls-rprx-vision"
  141. }
  142. entry := map[string]any{"email": c.Email}
  143. switch inbound.Protocol {
  144. case model.VLESS:
  145. if c.ID != "" {
  146. entry["id"] = c.ID
  147. }
  148. if flow != "" {
  149. entry["flow"] = flow
  150. }
  151. if c.Reverse != nil {
  152. entry["reverse"] = c.Reverse
  153. }
  154. case model.VMESS:
  155. if c.ID != "" {
  156. entry["id"] = c.ID
  157. }
  158. if c.Security != "" {
  159. entry["security"] = c.Security
  160. }
  161. case model.Trojan:
  162. if c.Password != "" {
  163. entry["password"] = c.Password
  164. }
  165. if flow != "" {
  166. entry["flow"] = flow
  167. }
  168. case model.Shadowsocks:
  169. if c.Password != "" {
  170. entry["password"] = c.Password
  171. }
  172. case model.Hysteria:
  173. if c.Auth != "" {
  174. entry["auth"] = c.Auth
  175. }
  176. }
  177. finalClients = append(finalClients, entry)
  178. }
  179. _, hadClients := settings["clients"]
  180. mutated := hadClients || len(finalClients) > 0
  181. if mutated {
  182. settings["clients"] = finalClients
  183. }
  184. if inboundCanHostFallbacks(inbound) {
  185. fallbacks, fbErr := s.inboundService.fallbackService.BuildFallbacksJSON(nil, inbound.Id)
  186. if fbErr != nil {
  187. return nil, fbErr
  188. }
  189. if len(fallbacks) > 0 {
  190. generic := make([]any, 0, len(fallbacks))
  191. for _, f := range fallbacks {
  192. generic = append(generic, f)
  193. }
  194. settings["fallbacks"] = generic
  195. mutated = true
  196. }
  197. }
  198. if mutated {
  199. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  200. if err != nil {
  201. return nil, err
  202. }
  203. inbound.Settings = string(modifiedSettings)
  204. }
  205. if len(inbound.StreamSettings) > 0 {
  206. // Unmarshal stream JSON
  207. var stream map[string]any
  208. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  209. // Remove the "settings" field under "tlsSettings" and "realitySettings"
  210. tlsSettings, ok1 := stream["tlsSettings"].(map[string]any)
  211. realitySettings, ok2 := stream["realitySettings"].(map[string]any)
  212. if ok1 || ok2 {
  213. if ok1 {
  214. delete(tlsSettings, "settings")
  215. } else if ok2 {
  216. delete(realitySettings, "settings")
  217. }
  218. }
  219. delete(stream, "externalProxy")
  220. newStream, err := json.MarshalIndent(stream, "", " ")
  221. if err != nil {
  222. return nil, err
  223. }
  224. inbound.StreamSettings = string(newStream)
  225. }
  226. if inbound.Protocol == model.Shadowsocks {
  227. if healed, ok := model.HealShadowsocksClientMethods(inbound.Settings); ok {
  228. inbound.Settings = healed
  229. }
  230. }
  231. inboundConfig := inbound.GenXrayInboundConfig()
  232. xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig)
  233. }
  234. // Merge subscription-derived outbounds (if any) into the final outbounds array.
  235. // These are additive: each subscription is placed before or after the template
  236. // outbounds based on its Prepend flag, ordered by Priority. Tags assigned by the
  237. // subscription service are kept stable across refreshes so that balancers and
  238. // routing rules continue to work.
  239. subSvc := &OutboundSubscriptionService{}
  240. if prepend, appendList, err := subSvc.activeOutboundsSplit(); err == nil && (len(prepend) > 0 || len(appendList) > 0) {
  241. mergeSubscriptionOutbounds(xrayConfig, prepend, appendList)
  242. }
  243. // Wire the panel's own HTTP traffic through the configured outbound, after
  244. // the subscription merge so subscription outbound tags are valid targets.
  245. if egressTag, err := s.settingService.GetPanelOutbound(); err != nil {
  246. logger.Warning("read panelOutbound setting failed:", err)
  247. } else if egressTag != "" {
  248. injectPanelEgress(xrayConfig, egressTag)
  249. }
  250. return xrayConfig, nil
  251. }
  252. // PanelEgressInboundTag is the tag of the loopback SOCKS inbound injected into
  253. // the generated config when a panel outbound is configured. The panel's own
  254. // HTTP clients dial through it to egress via the chosen outbound.
  255. const PanelEgressInboundTag = "panel-egress"
  256. // panelEgressBasePort is the first port tried for the egress bridge; ports
  257. // already taken by other inbounds in the generated config are skipped.
  258. const panelEgressBasePort = 62790
  259. // injectPanelEgress appends a loopback SOCKS inbound to the generated config
  260. // and prepends a routing rule sending it to outboundTag. Both live only in the
  261. // generated config — the stored template is never modified — and both are
  262. // hot-appliable, so changing the panel outbound never restarts the core.
  263. func injectPanelEgress(cfg *xray.Config, outboundTag string) {
  264. for i := range cfg.InboundConfigs {
  265. if cfg.InboundConfigs[i].Tag == PanelEgressInboundTag {
  266. logger.Warning("panel egress: inbound tag [", PanelEgressInboundTag, "] already exists, skipping injection")
  267. return
  268. }
  269. }
  270. // The rule must exist before the inbound takes traffic, otherwise the
  271. // bridge would silently egress through the default outbound instead.
  272. routing := map[string]any{}
  273. if len(cfg.RouterConfig) > 0 {
  274. if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
  275. logger.Warning("panel egress: routing section is unparsable, skipping injection:", err)
  276. return
  277. }
  278. }
  279. rules, _ := routing["rules"].([]any)
  280. rule := map[string]any{
  281. "type": "field",
  282. "inboundTag": []any{PanelEgressInboundTag},
  283. }
  284. // The configured tag may name a routing balancer instead of a concrete
  285. // outbound. A field rule can target either, so emit the matching key —
  286. // balancerTag load-balances the panel's own traffic across the balancer's
  287. // outbounds, while a plain outbound tag keeps the original behavior.
  288. if routingTagIsBalancer(routing, outboundTag) {
  289. rule["balancerTag"] = outboundTag
  290. } else {
  291. rule["outboundTag"] = outboundTag
  292. }
  293. routing["rules"] = append([]any{rule}, rules...)
  294. newRouting, err := json.Marshal(routing)
  295. if err != nil {
  296. logger.Warning("panel egress: failed to rebuild routing section, skipping injection:", err)
  297. return
  298. }
  299. cfg.RouterConfig = json_util.RawMessage(newRouting)
  300. used := make(map[int]struct{}, len(cfg.InboundConfigs))
  301. for i := range cfg.InboundConfigs {
  302. used[cfg.InboundConfigs[i].Port] = struct{}{}
  303. }
  304. port := panelEgressBasePort
  305. for {
  306. if _, taken := used[port]; !taken {
  307. break
  308. }
  309. port++
  310. }
  311. cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
  312. Listen: json_util.RawMessage(`"127.0.0.1"`),
  313. Port: port,
  314. Protocol: "socks",
  315. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  316. Tag: PanelEgressInboundTag,
  317. })
  318. }
  319. // routingTagIsBalancer reports whether tag names a balancer in the parsed
  320. // routing section. The panel-egress rule targets a balancer via balancerTag and
  321. // a concrete outbound via outboundTag, so the caller picks the key from this.
  322. func routingTagIsBalancer(routing map[string]any, tag string) bool {
  323. if tag == "" {
  324. return false
  325. }
  326. balancers, ok := routing["balancers"].([]any)
  327. if !ok {
  328. return false
  329. }
  330. for _, b := range balancers {
  331. bm, ok := b.(map[string]any)
  332. if !ok {
  333. continue
  334. }
  335. if t, ok := bm["tag"].(string); ok && t == tag {
  336. return true
  337. }
  338. }
  339. return false
  340. }
  341. // mergeSubscriptionOutbounds appends the subscription outbounds to the
  342. // OutboundConfigs array of the xray config. It works on the already-unmarshaled
  343. // template so that manually configured outbounds are never overwritten.
  344. //
  345. // Safety: if we cannot parse the template's outbounds array, we leave
  346. // OutboundConfigs exactly as it came from the template (we do not inject
  347. // subscription outbounds). This prevents us from accidentally dropping the
  348. // user's manually configured outbounds when the template is in a weird state.
  349. func mergeSubscriptionOutbounds(cfg *xray.Config, prepend, appendList []any) {
  350. if len(prepend) == 0 && len(appendList) == 0 {
  351. return
  352. }
  353. var templateOutbounds []any
  354. if len(cfg.OutboundConfigs) > 0 {
  355. if err := json.Unmarshal(cfg.OutboundConfigs, &templateOutbounds); err != nil {
  356. // Corrupt template outbounds — do not touch the field at all.
  357. // The user will see problems on Xray start / next save.
  358. return
  359. }
  360. }
  361. merged := make([]any, 0, len(prepend)+len(templateOutbounds)+len(appendList))
  362. merged = append(merged, prepend...)
  363. merged = append(merged, templateOutbounds...)
  364. merged = append(merged, appendList...)
  365. combined, err := json.MarshalIndent(merged, "", " ")
  366. if err != nil {
  367. return
  368. }
  369. cfg.OutboundConfigs = json_util.RawMessage(combined)
  370. }
  371. // ensureAPIServices guarantees the gRPC services the panel depends on are
  372. // listed in the generated config's api block: HandlerService and StatsService
  373. // have always been required for inbound/user management and traffic polling,
  374. // and RoutingService enables hot routing reload on templates saved before it
  375. // was added to the default template. The stored template itself is not
  376. // modified — only the generated runtime config.
  377. func ensureAPIServices(api json_util.RawMessage) json_util.RawMessage {
  378. if len(api) == 0 {
  379. // No api block means the panel's API integration is deliberately
  380. // disabled; don't resurrect it behind the user's back.
  381. return api
  382. }
  383. var parsed map[string]any
  384. if err := json.Unmarshal(api, &parsed); err != nil {
  385. return api
  386. }
  387. services, _ := parsed["services"].([]any)
  388. have := make(map[string]bool, len(services))
  389. for _, svc := range services {
  390. if name, ok := svc.(string); ok {
  391. have[name] = true
  392. }
  393. }
  394. added := false
  395. for _, name := range []string{"HandlerService", "StatsService", "RoutingService"} {
  396. if !have[name] {
  397. services = append(services, name)
  398. added = true
  399. }
  400. }
  401. if !added {
  402. return api
  403. }
  404. parsed["services"] = services
  405. out, err := json.Marshal(parsed)
  406. if err != nil {
  407. return api
  408. }
  409. return out
  410. }
  411. // ensureStatsPolicy guarantees every policy level in the generated config has
  412. // statsUserOnline enabled, so the core tracks per-email online IPs for the
  413. // panel's online view and access-log-free IP limiting. Generated clients carry
  414. // no explicit level, so level "0" is created when absent. The flag is panel
  415. // infrastructure and is forced on even over an explicit false in the template,
  416. // same as the api services above. An entirely missing or unparsable policy
  417. // block is left alone; the stored template itself is never modified — only the
  418. // generated runtime config.
  419. func ensureStatsPolicy(policy json_util.RawMessage) json_util.RawMessage {
  420. if len(policy) == 0 {
  421. return policy
  422. }
  423. var parsed map[string]any
  424. if err := json.Unmarshal(policy, &parsed); err != nil {
  425. return policy
  426. }
  427. levels, _ := parsed["levels"].(map[string]any)
  428. if levels == nil {
  429. levels = make(map[string]any)
  430. }
  431. if _, ok := levels["0"]; !ok {
  432. levels["0"] = map[string]any{}
  433. }
  434. changed := false
  435. for _, raw := range levels {
  436. level, ok := raw.(map[string]any)
  437. if !ok {
  438. continue
  439. }
  440. if enabled, ok := level["statsUserOnline"].(bool); !ok || !enabled {
  441. level["statsUserOnline"] = true
  442. changed = true
  443. }
  444. }
  445. if !changed {
  446. return policy
  447. }
  448. parsed["levels"] = levels
  449. out, err := json.Marshal(parsed)
  450. if err != nil {
  451. return policy
  452. }
  453. return out
  454. }
  455. func resolveXrayLogPaths(logCfg json_util.RawMessage) json_util.RawMessage {
  456. if len(logCfg) == 0 {
  457. return logCfg
  458. }
  459. var parsed map[string]any
  460. if err := json.Unmarshal(logCfg, &parsed); err != nil {
  461. return logCfg
  462. }
  463. changed := false
  464. for _, key := range []string{"access", "error"} {
  465. v, ok := parsed[key].(string)
  466. if !ok {
  467. continue
  468. }
  469. trimmed := strings.TrimSpace(v)
  470. if trimmed == "" || strings.EqualFold(trimmed, "none") {
  471. continue
  472. }
  473. base := path.Base(filepath.ToSlash(trimmed))
  474. if base == "" || base == "." || base == ".." || base == "/" {
  475. continue
  476. }
  477. confined := filepath.Join(config.GetLogFolder(), base)
  478. if confined == trimmed {
  479. continue
  480. }
  481. parsed[key] = confined
  482. changed = true
  483. }
  484. if !changed {
  485. return logCfg
  486. }
  487. out, err := json.Marshal(parsed)
  488. if err != nil {
  489. return logCfg
  490. }
  491. return out
  492. }
  493. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  494. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  495. if !s.IsXrayRunning() {
  496. err := errors.New("xray is not running")
  497. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  498. return nil, nil, err
  499. }
  500. apiPort := p.GetAPIPort()
  501. if err := s.xrayAPI.Init(apiPort); err != nil {
  502. logger.Debug("Failed to initialize Xray API:", err)
  503. return nil, nil, err
  504. }
  505. defer s.xrayAPI.Close()
  506. traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
  507. if err != nil {
  508. logger.Debug("Failed to fetch Xray traffic:", err)
  509. return nil, nil, err
  510. }
  511. return traffic, clientTraffic, nil
  512. }
  513. // GetOnlineUsers returns connection-based online users (email + source IPs)
  514. // from the running core's online-stats API. ok=false means the API is not
  515. // available — xray isn't running or the core predates the online-stats RPCs —
  516. // and callers must use the legacy traffic-delta / access-log paths. The
  517. // capability is probed lazily per process: an Unimplemented answer pins this
  518. // core as unsupported until the next restart, while transient errors leave the
  519. // capability undecided so a flaky poll can't lock in legacy mode.
  520. func (s *XrayService) GetOnlineUsers() ([]xray.OnlineUser, bool, error) {
  521. if !s.IsXrayRunning() {
  522. return nil, false, nil
  523. }
  524. if p.OnlineAPISupport() == xray.OnlineAPIUnsupported {
  525. return nil, false, nil
  526. }
  527. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  528. logger.Debug("Failed to initialize Xray API:", err)
  529. return nil, false, err
  530. }
  531. defer s.xrayAPI.Close()
  532. users, err := s.xrayAPI.GetOnlineUsers()
  533. if err != nil {
  534. if xray.IsUnimplementedErr(err) {
  535. p.SetOnlineAPISupport(xray.OnlineAPIUnsupported)
  536. logger.Info("xray core does not support the online-stats API; falling back to traffic-delta onlines and access-log IP limit")
  537. return nil, false, nil
  538. }
  539. logger.Debug("Failed to fetch Xray online users:", err)
  540. return nil, false, err
  541. }
  542. if p.OnlineAPISupport() == xray.OnlineAPIUnknown {
  543. p.SetOnlineAPISupport(xray.OnlineAPISupported)
  544. logger.Info("xray core supports the online-stats API; using connection-based onlines and access-log-free IP limit")
  545. }
  546. return users, true, nil
  547. }
  548. // BalancerStatus is the live view of one balancer for the panel UI. Running
  549. // is false when the balancer isn't present in the running core (e.g. xray is
  550. // stopped or the balancer hasn't been saved/applied yet).
  551. type BalancerStatus struct {
  552. Tag string `json:"tag"`
  553. Running bool `json:"running"`
  554. Override string `json:"override"`
  555. Selected []string `json:"selected"`
  556. }
  557. // GetBalancersStatus queries the running core for the live state of the
  558. // given balancer tags. Per-tag failures are reported as Running=false rather
  559. // than failing the whole call, so the UI can render saved-but-not-applied
  560. // balancers alongside live ones.
  561. func (s *XrayService) GetBalancersStatus(tags []string) ([]BalancerStatus, error) {
  562. statuses := make([]BalancerStatus, 0, len(tags))
  563. if !s.IsXrayRunning() {
  564. for _, tag := range tags {
  565. statuses = append(statuses, BalancerStatus{Tag: tag})
  566. }
  567. return statuses, nil
  568. }
  569. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  570. return nil, err
  571. }
  572. defer s.xrayAPI.Close()
  573. for _, tag := range tags {
  574. info, err := s.xrayAPI.GetBalancerInfo(tag)
  575. if err != nil {
  576. logger.Debug("get balancer info [", tag, "] failed:", err)
  577. statuses = append(statuses, BalancerStatus{Tag: tag})
  578. continue
  579. }
  580. statuses = append(statuses, BalancerStatus{
  581. Tag: tag,
  582. Running: true,
  583. Override: info.Override,
  584. Selected: info.Selected,
  585. })
  586. }
  587. return statuses, nil
  588. }
  589. // OverrideBalancer forces a balancer in the running core to use the given
  590. // outbound tag; an empty target clears the override.
  591. func (s *XrayService) OverrideBalancer(tag, target string) error {
  592. if !s.IsXrayRunning() {
  593. return errors.New("xray is not running")
  594. }
  595. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  596. return err
  597. }
  598. defer s.xrayAPI.Close()
  599. return s.xrayAPI.SetBalancerTarget(tag, target)
  600. }
  601. // TestRoute asks the running core which outbound its router picks for the
  602. // described connection.
  603. func (s *XrayService) TestRoute(req xray.RouteTestRequest) (*xray.RouteTestResult, error) {
  604. if !s.IsXrayRunning() {
  605. return nil, errors.New("xray is not running")
  606. }
  607. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  608. return nil, err
  609. }
  610. defer s.xrayAPI.Close()
  611. return s.xrayAPI.TestRoute(req)
  612. }
  613. // RestartXray reconciles the running Xray process with the current desired
  614. // config. When isForce is false it first tries to apply the changes through
  615. // the Xray gRPC API without restarting the process (inbounds, outbounds and
  616. // routing rules/balancers are hot-reloadable); only changes the core cannot
  617. // take at runtime — or a force request — stop and restart the process.
  618. func (s *XrayService) RestartXray(isForce bool) error {
  619. lock.Lock()
  620. defer lock.Unlock()
  621. logger.Debug("restart Xray, force:", isForce)
  622. isManuallyStopped.Store(false)
  623. xrayConfig, err := s.GetXrayConfig()
  624. if err != nil {
  625. return err
  626. }
  627. if s.IsXrayRunning() {
  628. configUnchanged := p.GetConfig().Equals(xrayConfig)
  629. if !isForce && configUnchanged && !isNeedXrayRestart.Load() {
  630. logger.Debug("It does not need to restart Xray")
  631. return nil
  632. }
  633. if !isForce && !configUnchanged && s.tryHotApply(xrayConfig) {
  634. logger.Info("Xray config changes applied through the core API, no restart needed")
  635. return nil
  636. }
  637. p.Stop()
  638. }
  639. p = xray.NewProcess(xrayConfig)
  640. result = ""
  641. s.xrayAPI.StatsLastValues = nil
  642. err = p.Start()
  643. if err != nil {
  644. return err
  645. }
  646. return nil
  647. }
  648. // tryHotApply attempts to reconcile the running Xray instance with newCfg
  649. // through the core gRPC API (HandlerService for inbounds/outbounds,
  650. // RoutingService for rules/balancers). It returns true when the running
  651. // instance now matches newCfg; on any failure it returns false and the
  652. // caller falls back to a full process restart, which cleans up whatever was
  653. // partially applied. Callers must hold the package-level lock.
  654. func (s *XrayService) tryHotApply(newCfg *xray.Config) bool {
  655. oldCfg := p.GetConfig()
  656. diff, ok := xray.ComputeHotDiff(oldCfg, newCfg)
  657. if !ok {
  658. logger.Debug("hot apply: config change is not API-applicable, falling back to restart")
  659. return false
  660. }
  661. if diff.Empty() {
  662. p.SetConfig(newCfg)
  663. return true
  664. }
  665. apiPort := p.GetAPIPort()
  666. if apiPort <= 0 {
  667. return false
  668. }
  669. // A dedicated client: s.xrayAPI may be in use by traffic polling on other
  670. // service instances and is reset around restarts.
  671. hotAPI := xray.XrayAPI{}
  672. if err := hotAPI.Init(apiPort); err != nil {
  673. logger.Debug("hot apply: failed to init xray api:", err)
  674. return false
  675. }
  676. defer hotAPI.Close()
  677. // Removals first so changed handlers and port swaps never collide with
  678. // the additions that follow.
  679. for _, tag := range diff.RemovedInboundTags {
  680. if err := hotAPI.DelInbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  681. logger.Info("hot apply: remove inbound [", tag, "] failed:", err)
  682. return false
  683. }
  684. }
  685. for _, tag := range diff.RemovedOutboundTags {
  686. if err := hotAPI.DelOutbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  687. logger.Info("hot apply: remove outbound [", tag, "] failed:", err)
  688. return false
  689. }
  690. }
  691. for _, ob := range diff.AddedOutbounds {
  692. if err := addOutboundReconciling(&hotAPI, ob); err != nil {
  693. logger.Info("hot apply: add outbound failed:", err)
  694. return false
  695. }
  696. }
  697. for _, ib := range diff.AddedInbounds {
  698. if err := addInboundReconciling(&hotAPI, ib); err != nil {
  699. logger.Info("hot apply: add inbound failed:", err)
  700. return false
  701. }
  702. }
  703. if diff.RoutingConfig != nil {
  704. if err := hotAPI.ApplyRoutingConfig(diff.RoutingConfig); err != nil {
  705. logger.Info("hot apply: apply routing config failed:", err)
  706. return false
  707. }
  708. }
  709. p.SetConfig(newCfg)
  710. return true
  711. }
  712. // addInboundReconciling adds an inbound, and on a tag conflict (the handler
  713. // was already created through the runtime API while the stored snapshot was
  714. // stale) replaces the existing handler instead.
  715. func addInboundReconciling(api *xray.XrayAPI, inbound []byte) error {
  716. err := api.AddInbound(inbound)
  717. if err == nil || !xray.IsExistingTagErr(err) {
  718. return err
  719. }
  720. var meta struct {
  721. Tag string `json:"tag"`
  722. }
  723. if jsonErr := json.Unmarshal(inbound, &meta); jsonErr != nil || meta.Tag == "" {
  724. return err
  725. }
  726. if delErr := api.DelInbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  727. return delErr
  728. }
  729. return api.AddInbound(inbound)
  730. }
  731. // addOutboundReconciling mirrors addInboundReconciling for outbounds.
  732. func addOutboundReconciling(api *xray.XrayAPI, outbound []byte) error {
  733. err := api.AddOutbound(outbound)
  734. if err == nil || !xray.IsExistingTagErr(err) {
  735. return err
  736. }
  737. var meta struct {
  738. Tag string `json:"tag"`
  739. }
  740. if jsonErr := json.Unmarshal(outbound, &meta); jsonErr != nil || meta.Tag == "" {
  741. return err
  742. }
  743. if delErr := api.DelOutbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  744. return delErr
  745. }
  746. return api.AddOutbound(outbound)
  747. }
  748. // StopXray stops the running Xray process.
  749. func (s *XrayService) StopXray() error {
  750. lock.Lock()
  751. defer lock.Unlock()
  752. isManuallyStopped.Store(true)
  753. logger.Debug("Attempting to stop Xray...")
  754. if s.IsXrayRunning() {
  755. return p.Stop()
  756. }
  757. return errors.New("xray is not running")
  758. }
  759. // SetToNeedRestart marks that Xray needs to be restarted.
  760. func (s *XrayService) SetToNeedRestart() {
  761. isNeedXrayRestart.Store(true)
  762. }
  763. // GetXrayAPIPort returns the port the local xray process is listening on
  764. // for its gRPC HandlerService, or 0 when xray isn't currently running.
  765. // Exposed for the runtime package's LocalRuntime adapter — runtime can't
  766. // reach into the package-level `p` directly without a service-package
  767. // import cycle.
  768. func (s *XrayService) GetXrayAPIPort() int {
  769. if p == nil || !p.IsRunning() {
  770. return 0
  771. }
  772. return p.GetAPIPort()
  773. }
  774. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  775. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  776. return isNeedXrayRestart.CompareAndSwap(true, false)
  777. }
  778. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  779. func (s *XrayService) DidXrayCrash() bool {
  780. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  781. }