xray.go 26 KB

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