xray.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "path"
  7. "path/filepath"
  8. "runtime"
  9. "strings"
  10. "sync"
  11. "github.com/mhsanaei/3x-ui/v3/internal/config"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  13. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  14. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  15. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  16. "go.uber.org/atomic"
  17. )
  18. var (
  19. p *xray.Process
  20. lock sync.Mutex
  21. isNeedXrayRestart atomic.Bool // Indicates that restart was requested for Xray
  22. isManuallyStopped atomic.Bool // Indicates that Xray was stopped manually from the panel
  23. result string
  24. )
  25. // XrayService provides business logic for Xray process management.
  26. // It handles starting, stopping, restarting Xray, and managing its configuration.
  27. type XrayService struct {
  28. inboundService InboundService
  29. settingService SettingService
  30. nodeService NodeService
  31. xrayAPI xray.XrayAPI
  32. }
  33. // IsXrayRunning checks if the Xray process is currently running.
  34. func (s *XrayService) IsXrayRunning() bool {
  35. return p != nil && p.IsRunning()
  36. }
  37. // XrayProcess returns the current Xray process instance (may be nil when Xray
  38. // is not running). It exposes the package-level process to callers outside this
  39. // package (e.g. the tgbot subpackage) without changing access semantics.
  40. func XrayProcess() *xray.Process {
  41. return p
  42. }
  43. // GetXrayErr returns the error from the Xray process, if any.
  44. func (s *XrayService) GetXrayErr() error {
  45. if p == nil {
  46. return nil
  47. }
  48. err := p.GetErr()
  49. if err == nil {
  50. return nil
  51. }
  52. if runtime.GOOS == "windows" && err.Error() == "exit status 1" {
  53. // exit status 1 on Windows means that Xray process was killed
  54. // as we kill process to stop in on Windows, this is not an error
  55. return nil
  56. }
  57. return err
  58. }
  59. // GetXrayResult returns the result string from the Xray process.
  60. func (s *XrayService) GetXrayResult() string {
  61. if result != "" {
  62. return result
  63. }
  64. if s.IsXrayRunning() {
  65. return ""
  66. }
  67. if p == nil {
  68. return ""
  69. }
  70. result = p.GetResult()
  71. if runtime.GOOS == "windows" && result == "exit status 1" {
  72. // exit status 1 on Windows means that Xray process was killed
  73. // as we kill process to stop in on Windows, this is not an error
  74. return ""
  75. }
  76. return result
  77. }
  78. // GetXrayVersion returns the version of the running Xray process.
  79. func (s *XrayService) GetXrayVersion() string {
  80. if p == nil {
  81. return "Unknown"
  82. }
  83. return p.GetXrayVersion()
  84. }
  85. // RemoveIndex removes an element at the specified index from a slice.
  86. // Returns a new slice with the element removed.
  87. func RemoveIndex(s []any, index int) []any {
  88. return append(s[:index], s[index+1:]...)
  89. }
  90. // GetXrayConfig retrieves and builds the Xray configuration from settings and inbounds.
  91. func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
  92. templateConfig, err := s.settingService.GetXrayConfigTemplate()
  93. if err != nil {
  94. return nil, err
  95. }
  96. xrayConfig := &xray.Config{}
  97. err = json.Unmarshal([]byte(templateConfig), xrayConfig)
  98. if err != nil {
  99. return nil, err
  100. }
  101. xrayConfig.LogConfig = resolveXrayLogPaths(xrayConfig.LogConfig)
  102. xrayConfig.API = ensureAPIServices(xrayConfig.API)
  103. xrayConfig.Policy = ensureStatsPolicy(xrayConfig.Policy)
  104. xrayConfig.RouterConfig = stripDisabledRules(xrayConfig.RouterConfig)
  105. // Template outbounds authored before the xray-core #6258 XHTTP rename may
  106. // still carry sessionPlacement/sessionKey; lift them too (same reason as
  107. // the per-inbound lift below).
  108. xrayConfig.OutboundConfigs = liftOutboundsXhttpSessionIDKeys(xrayConfig.OutboundConfigs)
  109. _, _, _ = s.inboundService.AddTraffic(nil, nil)
  110. inbounds, err := s.inboundService.GetAllInbounds()
  111. if err != nil {
  112. return nil, err
  113. }
  114. for _, inbound := range inbounds {
  115. if !inbound.Enable {
  116. continue
  117. }
  118. if inbound.NodeID != nil {
  119. continue
  120. }
  121. if inbound.Protocol == model.MTProto {
  122. continue
  123. }
  124. settings := map[string]any{}
  125. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  126. dbClients, listErr := s.inboundService.clientService.ListForInbound(nil, inbound.Id)
  127. if listErr != nil {
  128. return nil, listErr
  129. }
  130. clientStats := inbound.ClientStats
  131. enableMap := make(map[string]bool, len(clientStats))
  132. for _, clientTraffic := range clientStats {
  133. enableMap[clientTraffic.Email] = clientTraffic.Enable
  134. }
  135. var finalClients []any
  136. var wgPeers []any
  137. for i := range dbClients {
  138. c := dbClients[i]
  139. if enable, exists := enableMap[c.Email]; exists && !enable {
  140. logger.Infof("Remove Inbound User %s due to expiration or traffic limit", c.Email)
  141. continue
  142. }
  143. if !c.Enable {
  144. continue
  145. }
  146. flow := c.Flow
  147. if flow == "xtls-rprx-vision-udp443" {
  148. flow = "xtls-rprx-vision"
  149. }
  150. entry := map[string]any{"email": c.Email}
  151. switch inbound.Protocol {
  152. case model.VLESS:
  153. if c.ID != "" {
  154. entry["id"] = c.ID
  155. }
  156. if flow != "" {
  157. entry["flow"] = flow
  158. }
  159. if c.Reverse != nil {
  160. entry["reverse"] = c.Reverse
  161. }
  162. case model.VMESS:
  163. if c.ID != "" {
  164. entry["id"] = c.ID
  165. }
  166. if c.Security != "" {
  167. entry["security"] = c.Security
  168. }
  169. case model.Trojan:
  170. if c.Password != "" {
  171. entry["password"] = c.Password
  172. }
  173. if flow != "" {
  174. entry["flow"] = flow
  175. }
  176. case model.Shadowsocks:
  177. if c.Password != "" {
  178. entry["password"] = c.Password
  179. }
  180. case model.Hysteria:
  181. if c.Auth != "" {
  182. entry["auth"] = c.Auth
  183. }
  184. case model.WireGuard:
  185. wgPeers = append(wgPeers, model.WireguardPeerFromClient(c))
  186. continue
  187. }
  188. finalClients = append(finalClients, entry)
  189. }
  190. var mutated bool
  191. if inbound.Protocol == model.WireGuard {
  192. delete(settings, "clients")
  193. if wgPeers == nil {
  194. wgPeers = []any{}
  195. }
  196. settings["peers"] = wgPeers
  197. mutated = true
  198. } else {
  199. _, hadClients := settings["clients"]
  200. mutated = hadClients || len(finalClients) > 0
  201. if mutated {
  202. settings["clients"] = finalClients
  203. }
  204. }
  205. if inboundCanHostFallbacks(inbound) {
  206. fallbacks, fbErr := s.inboundService.fallbackService.BuildFallbacksJSON(nil, inbound.Id)
  207. if fbErr != nil {
  208. return nil, fbErr
  209. }
  210. if len(fallbacks) > 0 {
  211. generic := make([]any, 0, len(fallbacks))
  212. for _, f := range fallbacks {
  213. generic = append(generic, f)
  214. }
  215. settings["fallbacks"] = generic
  216. mutated = true
  217. }
  218. }
  219. if mutated {
  220. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  221. if err != nil {
  222. return nil, err
  223. }
  224. inbound.Settings = string(modifiedSettings)
  225. }
  226. if len(inbound.StreamSettings) > 0 {
  227. // Unmarshal stream JSON
  228. var stream map[string]any
  229. _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  230. // Remove the "settings" field under "tlsSettings" and "realitySettings"
  231. tlsSettings, ok1 := stream["tlsSettings"].(map[string]any)
  232. realitySettings, ok2 := stream["realitySettings"].(map[string]any)
  233. if ok1 || ok2 {
  234. if ok1 {
  235. delete(tlsSettings, "settings")
  236. } else if ok2 {
  237. delete(realitySettings, "settings")
  238. }
  239. }
  240. delete(stream, "externalProxy")
  241. // finalmask.tcp + REALITY panics Xray-core on the first connection
  242. // (XTLS/Xray-core#6453). AddInbound/UpdateInbound reject this
  243. // combination at save time, but a row saved before that guard
  244. // existed (upgrade, node sync, restored backup, direct DB edit)
  245. // would still crash Xray on the next restart without this — drop
  246. // it here too, the same way liftXhttpSessionIDKeys and
  247. // HealShadowsocksClientMethods heal other legacy data in place.
  248. if len(finalMaskRealityTcpMasks(stream)) > 0 {
  249. logger.Warningf("Inbound %q: dropping finalmask, incompatible with REALITY security (crashes Xray-core, see XTLS/Xray-core#6453)", inbound.Tag)
  250. delete(stream, "finalmask")
  251. }
  252. // xray-core v26.6.22 (#6258) renamed the XHTTP session keys and
  253. // kept no fallback. Lift legacy sessionPlacement/sessionKey onto the
  254. // new names here so inbounds stored before the rename keep working
  255. // without the admin re-saving them.
  256. liftXhttpSessionIDKeys(stream)
  257. newStream, err := json.MarshalIndent(stream, "", " ")
  258. if err != nil {
  259. return nil, err
  260. }
  261. inbound.StreamSettings = string(newStream)
  262. }
  263. if inbound.Protocol == model.Shadowsocks {
  264. if healed, ok := model.HealShadowsocksClientMethods(inbound.Settings); ok {
  265. inbound.Settings = healed
  266. }
  267. }
  268. inboundConfig := inbound.GenXrayInboundConfig()
  269. xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig)
  270. }
  271. // Merge subscription-derived outbounds (if any) into the final outbounds array.
  272. // These are additive: each subscription is placed before or after the template
  273. // outbounds based on its Prepend flag, ordered by Priority. Tags assigned by the
  274. // subscription service are kept stable across refreshes so that balancers and
  275. // routing rules continue to work.
  276. subSvc := &OutboundSubscriptionService{}
  277. if prepend, appendList, err := subSvc.activeOutboundsSplit(); err == nil && (len(prepend) > 0 || len(appendList) > 0) {
  278. mergeSubscriptionOutbounds(xrayConfig, prepend, appendList)
  279. }
  280. // Route opted-in local mtproto inbounds through the core's router. Each one
  281. // gets a loopback SOCKS bridge — tagged with the inbound's own tag so it is
  282. // matchable in routing rules — that its mtg sidecar dials Telegram through.
  283. // Done after the subscription merge so a selected subscription outbound (or
  284. // balancer) is a valid rule target.
  285. for i := range inbounds {
  286. inbound := inbounds[i]
  287. if inbound.Protocol != model.MTProto || !inbound.Enable || inbound.NodeID != nil {
  288. continue
  289. }
  290. injectMtprotoEgress(xrayConfig, inbound)
  291. }
  292. // Wire the panel's own HTTP traffic through the configured outbound, after
  293. // the subscription merge so subscription outbound tags are valid targets.
  294. if egressTag, err := s.settingService.GetPanelOutbound(); err != nil {
  295. logger.Warning("read panelOutbound setting failed:", err)
  296. } else if egressTag != "" {
  297. injectPanelEgress(xrayConfig, egressTag)
  298. }
  299. nodes, err := s.nodeService.GetAll()
  300. if err != nil {
  301. logger.Warning("read nodes for egress injection failed:", err)
  302. } else {
  303. injectNodeEgresses(xrayConfig, nodes)
  304. }
  305. return xrayConfig, nil
  306. }
  307. // PanelEgressInboundTag is the tag of the loopback SOCKS inbound injected into
  308. // the generated config when a panel outbound is configured. The panel's own
  309. // HTTP clients dial through it to egress via the chosen outbound.
  310. const PanelEgressInboundTag = "panel-egress"
  311. // panelEgressBasePort is the first port tried for the egress bridge; ports
  312. // already taken by other inbounds in the generated config are skipped.
  313. const panelEgressBasePort = 62790
  314. // injectPanelEgress appends a loopback SOCKS inbound and routing rule only when
  315. // outboundTag resolves in the final outbound or balancer set. Otherwise the
  316. // entire injection is skipped. Generated state is hot-appliable and never
  317. // modifies the stored template or restarts the core.
  318. func injectPanelEgress(cfg *xray.Config, outboundTag string) {
  319. for i := range cfg.InboundConfigs {
  320. if cfg.InboundConfigs[i].Tag == PanelEgressInboundTag {
  321. logger.Warning("panel egress: inbound tag [", PanelEgressInboundTag, "] already exists, skipping injection")
  322. return
  323. }
  324. }
  325. // The rule must exist before the inbound takes traffic, otherwise the
  326. // bridge would silently egress through the default outbound instead.
  327. routing := map[string]any{}
  328. if len(cfg.RouterConfig) > 0 {
  329. if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
  330. logger.Warning("panel egress: routing section is unparsable, skipping injection:", err)
  331. return
  332. }
  333. }
  334. if !routingTargetExists(routing, cfg.OutboundConfigs, outboundTag) {
  335. logger.Warning("panel egress: target tag [", outboundTag, "] not found, skipping injection")
  336. return
  337. }
  338. rules, _ := routing["rules"].([]any)
  339. rule := map[string]any{
  340. "type": "field",
  341. "inboundTag": []any{PanelEgressInboundTag},
  342. }
  343. // The configured tag may name a routing balancer instead of a concrete
  344. // outbound. A field rule can target either, so emit the matching key —
  345. // balancerTag load-balances the panel's own traffic across the balancer's
  346. // outbounds, while a plain outbound tag keeps the original behavior.
  347. if routingTagIsBalancer(routing, outboundTag) {
  348. rule["balancerTag"] = outboundTag
  349. } else {
  350. rule["outboundTag"] = outboundTag
  351. }
  352. routing["rules"] = append([]any{rule}, rules...)
  353. newRouting, err := json.Marshal(routing)
  354. if err != nil {
  355. logger.Warning("panel egress: failed to rebuild routing section, skipping injection:", err)
  356. return
  357. }
  358. cfg.RouterConfig = json_util.RawMessage(newRouting)
  359. used := make(map[int]struct{}, len(cfg.InboundConfigs))
  360. for i := range cfg.InboundConfigs {
  361. used[cfg.InboundConfigs[i].Port] = struct{}{}
  362. }
  363. port := panelEgressBasePort
  364. for {
  365. if _, taken := used[port]; !taken {
  366. break
  367. }
  368. port++
  369. }
  370. cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
  371. Listen: json_util.RawMessage(`"127.0.0.1"`),
  372. Port: port,
  373. Protocol: "socks",
  374. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  375. Tag: PanelEgressInboundTag,
  376. })
  377. }
  378. func outboundTagExists(outbounds json_util.RawMessage, tag string) bool {
  379. var parsed []struct {
  380. Tag string `json:"tag"`
  381. }
  382. if tag == "" || json.Unmarshal(outbounds, &parsed) != nil {
  383. return false
  384. }
  385. for _, outbound := range parsed {
  386. if outbound.Tag == tag {
  387. return true
  388. }
  389. }
  390. return false
  391. }
  392. func routingTargetExists(routing map[string]any, outbounds json_util.RawMessage, tag string) bool {
  393. return routingTagIsBalancer(routing, tag) || outboundTagExists(outbounds, tag)
  394. }
  395. // NodeEgressInboundTag returns the loopback SOCKS inbound tag for a given node.
  396. func NodeEgressInboundTag(nodeID int) string {
  397. return fmt.Sprintf("node-egress-%d", nodeID)
  398. }
  399. // nodeEgressBasePort is the first port tried for node egress bridges.
  400. const nodeEgressBasePort = 62800
  401. // injectNodeEgresses appends a loopback SOCKS inbound per enabled node that has
  402. // an OutboundTag, and prepends a routing rule sending that inbound's traffic to
  403. // the selected outbound tag. These bridges are hot-appliable.
  404. func injectNodeEgresses(cfg *xray.Config, nodes []*model.Node) {
  405. routing := map[string]any{}
  406. if len(cfg.RouterConfig) > 0 {
  407. if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
  408. logger.Warning("node egress: routing section is unparsable, skipping injection:", err)
  409. return
  410. }
  411. }
  412. used := make(map[int]struct{}, len(cfg.InboundConfigs))
  413. usedTags := make(map[string]struct{}, len(cfg.InboundConfigs))
  414. for i := range cfg.InboundConfigs {
  415. used[cfg.InboundConfigs[i].Port] = struct{}{}
  416. usedTags[cfg.InboundConfigs[i].Tag] = struct{}{}
  417. }
  418. rules, _ := routing["rules"].([]any)
  419. newRules := make([]any, 0)
  420. for _, n := range nodes {
  421. if !n.Enable || n.OutboundTag == "" {
  422. continue
  423. }
  424. if !routingTargetExists(routing, cfg.OutboundConfigs, n.OutboundTag) {
  425. logger.Warning("node egress: target tag [", n.OutboundTag, "] not found, skipping node [", n.Id, "]")
  426. continue
  427. }
  428. tag := NodeEgressInboundTag(n.Id)
  429. if _, exists := usedTags[tag]; exists {
  430. logger.Warning("node egress: inbound tag [", tag, "] already exists, skipping")
  431. continue
  432. }
  433. usedTags[tag] = struct{}{}
  434. rule := map[string]any{
  435. "type": "field",
  436. "inboundTag": []any{tag},
  437. }
  438. if routingTagIsBalancer(routing, n.OutboundTag) {
  439. rule["balancerTag"] = n.OutboundTag
  440. } else {
  441. rule["outboundTag"] = n.OutboundTag
  442. }
  443. newRules = append(newRules, rule)
  444. port := nodeEgressBasePort + n.Id
  445. for {
  446. if _, taken := used[port]; !taken {
  447. break
  448. }
  449. port++
  450. }
  451. used[port] = struct{}{}
  452. cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
  453. Listen: json_util.RawMessage(`"127.0.0.1"`),
  454. Port: port,
  455. Protocol: "socks",
  456. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  457. Tag: tag,
  458. })
  459. }
  460. if len(newRules) == 0 {
  461. return
  462. }
  463. routing["rules"] = append(newRules, rules...)
  464. newRouting, err := json.Marshal(routing)
  465. if err != nil {
  466. logger.Warning("node egress: failed to rebuild routing section, skipping injection:", err)
  467. return
  468. }
  469. cfg.RouterConfig = json_util.RawMessage(newRouting)
  470. }
  471. // routingTagIsBalancer reports whether tag names a balancer in the parsed
  472. // routing section. The panel-egress rule targets a balancer via balancerTag and
  473. // a concrete outbound via outboundTag, so the caller picks the key from this.
  474. func routingTagIsBalancer(routing map[string]any, tag string) bool {
  475. if tag == "" {
  476. return false
  477. }
  478. balancers, ok := routing["balancers"].([]any)
  479. if !ok {
  480. return false
  481. }
  482. for _, b := range balancers {
  483. bm, ok := b.(map[string]any)
  484. if !ok {
  485. continue
  486. }
  487. if t, ok := bm["tag"].(string); ok && t == tag {
  488. return true
  489. }
  490. }
  491. return false
  492. }
  493. // mtprotoEgressSocksSettings is the loopback SOCKS server a routed mtproto
  494. // inbound exposes for its mtg sidecar to dial Telegram through. mtg makes plain
  495. // TCP connections, so UDP is left off (matching the panel egress bridge).
  496. const mtprotoEgressSocksSettings = `{"auth":"noauth","udp":false}`
  497. // injectMtprotoEgress wires one routed mtproto inbound into the generated
  498. // config after any selected outbound resolves in the final target set. Invalid
  499. // selected targets or routing data skip the entire injection; without a selected
  500. // outbound, the bridge retains default-route behavior. Generated state remains
  501. // hot-appliable, leaves the stored template untouched, and never forces a full
  502. // Xray restart. Mirrors injectPanelEgress.
  503. func injectMtprotoEgress(cfg *xray.Config, inbound *model.Inbound) {
  504. var parsed struct {
  505. RouteThroughXray bool `json:"routeThroughXray"`
  506. RouteXrayPort int `json:"routeXrayPort"`
  507. OutboundTag string `json:"outboundTag"`
  508. }
  509. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  510. return
  511. }
  512. if !parsed.RouteThroughXray || parsed.RouteXrayPort <= 0 || inbound.Tag == "" {
  513. return
  514. }
  515. tag := inbound.Tag
  516. for i := range cfg.InboundConfigs {
  517. if cfg.InboundConfigs[i].Tag == tag {
  518. logger.Warning("mtproto egress: inbound tag [", tag, "] already present in generated config, skipping bridge")
  519. return
  520. }
  521. }
  522. if parsed.OutboundTag != "" {
  523. routing := map[string]any{}
  524. if len(cfg.RouterConfig) > 0 {
  525. if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
  526. logger.Warning("mtproto egress: routing section is unparsable, skipping injection:", err)
  527. return
  528. }
  529. }
  530. if !routingTargetExists(routing, cfg.OutboundConfigs, parsed.OutboundTag) {
  531. logger.Warning("mtproto egress: target tag [", parsed.OutboundTag, "] not found, skipping injection")
  532. return
  533. }
  534. rules, _ := routing["rules"].([]any)
  535. rule := map[string]any{
  536. "type": "field",
  537. "inboundTag": []any{tag},
  538. }
  539. if routingTagIsBalancer(routing, parsed.OutboundTag) {
  540. rule["balancerTag"] = parsed.OutboundTag
  541. } else {
  542. rule["outboundTag"] = parsed.OutboundTag
  543. }
  544. routing["rules"] = append([]any{rule}, rules...)
  545. newRouting, err := json.Marshal(routing)
  546. if err != nil {
  547. logger.Warning("mtproto egress: failed to rebuild routing section, skipping injection:", err)
  548. return
  549. }
  550. cfg.RouterConfig = json_util.RawMessage(newRouting)
  551. }
  552. cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
  553. Listen: json_util.RawMessage(`"127.0.0.1"`),
  554. Port: parsed.RouteXrayPort,
  555. Protocol: "socks",
  556. Settings: json_util.RawMessage(mtprotoEgressSocksSettings),
  557. Tag: tag,
  558. })
  559. }
  560. // mergeSubscriptionOutbounds appends the subscription outbounds to the
  561. // OutboundConfigs array of the xray config. It works on the already-unmarshaled
  562. // template so that manually configured outbounds are never overwritten.
  563. //
  564. // Safety: if we cannot parse the template's outbounds array, we leave
  565. // OutboundConfigs exactly as it came from the template (we do not inject
  566. // subscription outbounds). This prevents us from accidentally dropping the
  567. // user's manually configured outbounds when the template is in a weird state.
  568. func mergeSubscriptionOutbounds(cfg *xray.Config, prepend, appendList []any) {
  569. if len(prepend) == 0 && len(appendList) == 0 {
  570. return
  571. }
  572. var templateOutbounds []any
  573. if len(cfg.OutboundConfigs) > 0 {
  574. if err := json.Unmarshal(cfg.OutboundConfigs, &templateOutbounds); err != nil {
  575. // Corrupt template outbounds — do not touch the field at all.
  576. // The user will see problems on Xray start / next save.
  577. return
  578. }
  579. }
  580. var merged []any
  581. merged = append(merged, prepend...)
  582. merged = append(merged, templateOutbounds...)
  583. merged = append(merged, appendList...)
  584. combined, err := json.MarshalIndent(merged, "", " ")
  585. if err != nil {
  586. return
  587. }
  588. cfg.OutboundConfigs = json_util.RawMessage(combined)
  589. }
  590. // ensureAPIServices guarantees the gRPC services the panel depends on are
  591. // listed in the generated config's api block: HandlerService and StatsService
  592. // have always been required for inbound/user management and traffic polling,
  593. // and RoutingService enables hot routing reload on templates saved before it
  594. // was added to the default template. The stored template itself is not
  595. // modified — only the generated runtime config.
  596. func ensureAPIServices(api json_util.RawMessage) json_util.RawMessage {
  597. if len(api) == 0 {
  598. // No api block means the panel's API integration is deliberately
  599. // disabled; don't resurrect it behind the user's back.
  600. return api
  601. }
  602. var parsed map[string]any
  603. if err := json.Unmarshal(api, &parsed); err != nil {
  604. return api
  605. }
  606. services, _ := parsed["services"].([]any)
  607. have := make(map[string]bool, len(services))
  608. for _, svc := range services {
  609. if name, ok := svc.(string); ok {
  610. have[name] = true
  611. }
  612. }
  613. added := false
  614. for _, name := range []string{"HandlerService", "StatsService", "RoutingService"} {
  615. if !have[name] {
  616. services = append(services, name)
  617. added = true
  618. }
  619. }
  620. if !added {
  621. return api
  622. }
  623. parsed["services"] = services
  624. out, err := json.Marshal(parsed)
  625. if err != nil {
  626. return api
  627. }
  628. return out
  629. }
  630. // ensureStatsPolicy guarantees every policy level in the generated config has
  631. // statsUserOnline enabled, so the core tracks per-email online IPs for the
  632. // panel's online view and access-log-free IP limiting. Generated clients carry
  633. // no explicit level, so level "0" is created when absent. The flag is panel
  634. // infrastructure and is forced on even over an explicit false in the template,
  635. // same as the api services above. An entirely missing or unparsable policy
  636. // block is left alone; the stored template itself is never modified — only the
  637. // generated runtime config.
  638. func ensureStatsPolicy(policy json_util.RawMessage) json_util.RawMessage {
  639. if len(policy) == 0 {
  640. return policy
  641. }
  642. var parsed map[string]any
  643. if err := json.Unmarshal(policy, &parsed); err != nil {
  644. return policy
  645. }
  646. levels, _ := parsed["levels"].(map[string]any)
  647. if levels == nil {
  648. levels = make(map[string]any)
  649. }
  650. if _, ok := levels["0"]; !ok {
  651. levels["0"] = map[string]any{}
  652. }
  653. changed := false
  654. for _, raw := range levels {
  655. level, ok := raw.(map[string]any)
  656. if !ok {
  657. continue
  658. }
  659. if enabled, ok := level["statsUserOnline"].(bool); !ok || !enabled {
  660. level["statsUserOnline"] = true
  661. changed = true
  662. }
  663. }
  664. if !changed {
  665. return policy
  666. }
  667. parsed["levels"] = levels
  668. out, err := json.Marshal(parsed)
  669. if err != nil {
  670. return policy
  671. }
  672. return out
  673. }
  674. func resolveXrayLogPaths(logCfg json_util.RawMessage) json_util.RawMessage {
  675. if len(logCfg) == 0 {
  676. return logCfg
  677. }
  678. var parsed map[string]any
  679. if err := json.Unmarshal(logCfg, &parsed); err != nil {
  680. return logCfg
  681. }
  682. changed := false
  683. for _, key := range []string{"access", "error"} {
  684. v, ok := parsed[key].(string)
  685. if !ok {
  686. continue
  687. }
  688. trimmed := strings.TrimSpace(v)
  689. if trimmed == "" || strings.EqualFold(trimmed, "none") {
  690. continue
  691. }
  692. base := path.Base(filepath.ToSlash(trimmed))
  693. if base == "" || base == "." || base == ".." || base == "/" {
  694. continue
  695. }
  696. confined := filepath.Join(config.GetLogFolder(), base)
  697. if confined == trimmed {
  698. continue
  699. }
  700. parsed[key] = confined
  701. changed = true
  702. }
  703. if !changed {
  704. return logCfg
  705. }
  706. out, err := json.Marshal(parsed)
  707. if err != nil {
  708. return logCfg
  709. }
  710. return out
  711. }
  712. // stripDisabledRules removes routing rules marked `enabled: false` from the
  713. // generated runtime config and strips the panel-only `enabled` key from the
  714. // rest, since xray-core has no such field. The internal api rule is always
  715. // kept (see isApiRule) so traffic stats can't be toggled off. The stored
  716. // template is untouched — only the generated config is filtered.
  717. func stripDisabledRules(routerCfg json_util.RawMessage) json_util.RawMessage {
  718. if len(routerCfg) == 0 {
  719. return routerCfg
  720. }
  721. var parsed map[string]any
  722. if err := json.Unmarshal(routerCfg, &parsed); err != nil {
  723. return routerCfg
  724. }
  725. rules, ok := parsed["rules"].([]any)
  726. if !ok || len(rules) == 0 {
  727. return routerCfg
  728. }
  729. var activeRules []any
  730. changed := false
  731. for _, rawRule := range rules {
  732. rule, ok := rawRule.(map[string]any)
  733. if !ok {
  734. activeRules = append(activeRules, rawRule)
  735. continue
  736. }
  737. if enabledRaw, exists := rule["enabled"]; exists {
  738. // The internal api rule carries traffic stats and must never be
  739. // dropped, even if it was somehow marked disabled.
  740. enabled, ok := enabledRaw.(bool)
  741. if ok && !enabled && !isApiRule(rule) {
  742. changed = true
  743. continue
  744. }
  745. delete(rule, "enabled")
  746. changed = true
  747. }
  748. activeRules = append(activeRules, rule)
  749. }
  750. if !changed {
  751. return routerCfg
  752. }
  753. parsed["rules"] = activeRules
  754. out, err := json.Marshal(parsed)
  755. if err != nil {
  756. return routerCfg
  757. }
  758. return out
  759. }
  760. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  761. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  762. if !s.IsXrayRunning() {
  763. err := errors.New("xray is not running")
  764. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  765. return nil, nil, err
  766. }
  767. apiPort := p.GetAPIPort()
  768. if err := s.xrayAPI.Init(apiPort); err != nil {
  769. logger.Debug("Failed to initialize Xray API:", err)
  770. return nil, nil, err
  771. }
  772. defer s.xrayAPI.Close()
  773. traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
  774. if err != nil {
  775. logger.Debug("Failed to fetch Xray traffic:", err)
  776. return nil, nil, err
  777. }
  778. return traffic, clientTraffic, nil
  779. }
  780. // GetOnlineUsers returns connection-based online users (email + source IPs)
  781. // from the running core's online-stats API. ok=false means the API is not
  782. // available — xray isn't running or the core predates the online-stats RPCs —
  783. // and callers must use the legacy traffic-delta / access-log paths. The
  784. // capability is probed lazily per process: an Unimplemented answer pins this
  785. // core as unsupported until the next restart, while transient errors leave the
  786. // capability undecided so a flaky poll can't lock in legacy mode.
  787. func (s *XrayService) GetOnlineUsers() ([]xray.OnlineUser, bool, error) {
  788. if !s.IsXrayRunning() {
  789. return nil, false, nil
  790. }
  791. if p.OnlineAPISupport() == xray.OnlineAPIUnsupported {
  792. return nil, false, nil
  793. }
  794. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  795. logger.Debug("Failed to initialize Xray API:", err)
  796. return nil, false, err
  797. }
  798. defer s.xrayAPI.Close()
  799. users, err := s.xrayAPI.GetOnlineUsers()
  800. if err != nil {
  801. if xray.IsUnimplementedErr(err) {
  802. p.SetOnlineAPISupport(xray.OnlineAPIUnsupported)
  803. logger.Info("xray core does not support the online-stats API; falling back to traffic-delta onlines and access-log IP limit")
  804. return nil, false, nil
  805. }
  806. logger.Debug("Failed to fetch Xray online users:", err)
  807. return nil, false, err
  808. }
  809. if p.OnlineAPISupport() == xray.OnlineAPIUnknown {
  810. p.SetOnlineAPISupport(xray.OnlineAPISupported)
  811. logger.Info("xray core supports the online-stats API; using connection-based onlines and access-log-free IP limit")
  812. }
  813. return users, true, nil
  814. }
  815. // BalancerStatus is the live view of one balancer for the panel UI. Running
  816. // is false when the balancer isn't present in the running core (e.g. xray is
  817. // stopped or the balancer hasn't been saved/applied yet).
  818. type BalancerStatus struct {
  819. Tag string `json:"tag"`
  820. Running bool `json:"running"`
  821. Override string `json:"override"`
  822. Selected []string `json:"selected"`
  823. }
  824. // GetBalancersStatus queries the running core for the live state of the
  825. // given balancer tags. Per-tag failures are reported as Running=false rather
  826. // than failing the whole call, so the UI can render saved-but-not-applied
  827. // balancers alongside live ones.
  828. func (s *XrayService) GetBalancersStatus(tags []string) ([]BalancerStatus, error) {
  829. statuses := make([]BalancerStatus, 0, len(tags))
  830. if !s.IsXrayRunning() {
  831. for _, tag := range tags {
  832. statuses = append(statuses, BalancerStatus{Tag: tag})
  833. }
  834. return statuses, nil
  835. }
  836. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  837. return nil, err
  838. }
  839. defer s.xrayAPI.Close()
  840. for _, tag := range tags {
  841. info, err := s.xrayAPI.GetBalancerInfo(tag)
  842. if err != nil {
  843. logger.Debug("get balancer info [", tag, "] failed:", err)
  844. statuses = append(statuses, BalancerStatus{Tag: tag})
  845. continue
  846. }
  847. statuses = append(statuses, BalancerStatus{
  848. Tag: tag,
  849. Running: true,
  850. Override: info.Override,
  851. Selected: info.Selected,
  852. })
  853. }
  854. return statuses, nil
  855. }
  856. // OverrideBalancer forces a balancer in the running core to use the given
  857. // outbound tag; an empty target clears the override. When target names
  858. // another balancer, the override resolves to the loopback outbound that
  859. // routes traffic through the target balancer via the routing rules.
  860. func (s *XrayService) OverrideBalancer(tag, target string) error {
  861. if !s.IsXrayRunning() {
  862. return errors.New("xray is not running")
  863. }
  864. if target != "" {
  865. resolved, err := s.resolveOverrideTarget(target)
  866. if err != nil {
  867. return err
  868. }
  869. if resolved != "" {
  870. target = resolved
  871. }
  872. }
  873. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  874. return err
  875. }
  876. defer s.xrayAPI.Close()
  877. return s.xrayAPI.SetBalancerTarget(tag, target)
  878. }
  879. // resolveOverrideTarget checks if target names a balancer and, if so,
  880. // returns the loopback outbound tag that routes to it through the
  881. // routing rules. Returns empty if target is already a concrete outbound.
  882. func (s *XrayService) resolveOverrideTarget(target string) (string, error) {
  883. template, err := s.settingService.GetXrayConfigTemplate()
  884. if err != nil {
  885. return "", err
  886. }
  887. var cfg map[string]any
  888. if err := json.Unmarshal([]byte(template), &cfg); err != nil {
  889. return "", err
  890. }
  891. routing, _ := cfg["routing"].(map[string]any)
  892. if routing == nil {
  893. return "", nil
  894. }
  895. rules, _ := routing["rules"].([]any)
  896. for _, r := range rules {
  897. rule, ok := r.(map[string]any)
  898. if !ok {
  899. continue
  900. }
  901. if rule["balancerTag"] != target {
  902. continue
  903. }
  904. inboundTags, ok := rule["inboundTag"].([]any)
  905. if !ok || len(inboundTags) == 0 {
  906. continue
  907. }
  908. if lbTag, ok := inboundTags[0].(string); ok && strings.HasPrefix(lbTag, "_bl_") {
  909. return lbTag, nil
  910. }
  911. }
  912. return "", nil
  913. }
  914. // TestRoute asks the running core which outbound its router picks for the
  915. // described connection.
  916. func (s *XrayService) TestRoute(req xray.RouteTestRequest) (*xray.RouteTestResult, error) {
  917. if !s.IsXrayRunning() {
  918. return nil, errors.New("xray is not running")
  919. }
  920. if err := s.xrayAPI.Init(p.GetAPIPort()); err != nil {
  921. return nil, err
  922. }
  923. defer s.xrayAPI.Close()
  924. return s.xrayAPI.TestRoute(req)
  925. }
  926. // RestartXray reconciles the running Xray process with the current desired
  927. // config. When isForce is false it first tries to apply the changes through
  928. // the Xray gRPC API without restarting the process (inbounds, outbounds and
  929. // routing rules/balancers are hot-reloadable); only changes the core cannot
  930. // take at runtime — or a force request — stop and restart the process.
  931. func (s *XrayService) RestartXray(isForce bool) error {
  932. lock.Lock()
  933. defer lock.Unlock()
  934. logger.Debug("restart Xray, force:", isForce)
  935. if !isForce && isManuallyStopped.Load() {
  936. return nil
  937. }
  938. isManuallyStopped.Store(false)
  939. xrayConfig, err := s.GetXrayConfig()
  940. if err != nil {
  941. return err
  942. }
  943. if s.IsXrayRunning() {
  944. configUnchanged := p.GetConfig().Equals(xrayConfig)
  945. if !isForce && configUnchanged && !isNeedXrayRestart.Load() {
  946. logger.Debug("It does not need to restart Xray")
  947. return nil
  948. }
  949. if !isForce && !configUnchanged && s.tryHotApply(xrayConfig) {
  950. logger.Info("Xray config changes applied through the core API, no restart needed")
  951. return nil
  952. }
  953. _ = p.Stop()
  954. }
  955. p = xray.NewProcess(xrayConfig)
  956. result = ""
  957. s.xrayAPI.StatsLastValues = nil
  958. err = p.Start()
  959. if err != nil {
  960. return err
  961. }
  962. return nil
  963. }
  964. // tryHotApply attempts to reconcile the running Xray instance with newCfg
  965. // through the core gRPC API (HandlerService for inbounds/outbounds,
  966. // RoutingService for rules/balancers). It returns true when the running
  967. // instance now matches newCfg; on any failure it returns false and the
  968. // caller falls back to a full process restart, which cleans up whatever was
  969. // partially applied. Callers must hold the package-level lock.
  970. func (s *XrayService) tryHotApply(newCfg *xray.Config) bool {
  971. oldCfg := p.GetConfig()
  972. diff, ok := xray.ComputeHotDiff(oldCfg, newCfg)
  973. if !ok {
  974. logger.Debug("hot apply: config change is not API-applicable, falling back to restart")
  975. return false
  976. }
  977. if diff.Empty() {
  978. p.SetConfig(newCfg)
  979. return true
  980. }
  981. apiPort := p.GetAPIPort()
  982. if apiPort <= 0 {
  983. return false
  984. }
  985. // A dedicated client: s.xrayAPI may be in use by traffic polling on other
  986. // service instances and is reset around restarts.
  987. hotAPI := xray.XrayAPI{}
  988. if err := hotAPI.Init(apiPort); err != nil {
  989. logger.Debug("hot apply: failed to init xray api:", err)
  990. return false
  991. }
  992. defer hotAPI.Close()
  993. // Removals first so changed handlers and port swaps never collide with
  994. // the additions that follow.
  995. for _, u := range diff.RemovedUsers {
  996. if err := hotAPI.RemoveUser(u.Tag, u.Email); err != nil && !xray.IsMissingHandlerErr(err) {
  997. logger.Info("hot apply: remove user [", u.Email, "] from [", u.Tag, "] failed:", err)
  998. return false
  999. }
  1000. }
  1001. for _, tag := range diff.RemovedInboundTags {
  1002. if err := hotAPI.DelInbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  1003. logger.Info("hot apply: remove inbound [", tag, "] failed:", err)
  1004. return false
  1005. }
  1006. }
  1007. for _, tag := range diff.RemovedOutboundTags {
  1008. if err := hotAPI.DelOutbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  1009. logger.Info("hot apply: remove outbound [", tag, "] failed:", err)
  1010. return false
  1011. }
  1012. }
  1013. for _, ob := range diff.AddedOutbounds {
  1014. if err := addOutboundReconciling(&hotAPI, ob); err != nil {
  1015. logger.Info("hot apply: add outbound failed:", err)
  1016. return false
  1017. }
  1018. }
  1019. for _, ib := range diff.AddedInbounds {
  1020. if err := addInboundReconciling(&hotAPI, ib); err != nil {
  1021. logger.Info("hot apply: add inbound failed:", err)
  1022. return false
  1023. }
  1024. }
  1025. for _, u := range diff.AddedUsers {
  1026. if err := addUserReconciling(&hotAPI, u); err != nil {
  1027. logger.Info("hot apply: add user [", u.Email, "] to [", u.Tag, "] failed:", err)
  1028. return false
  1029. }
  1030. }
  1031. if diff.RoutingConfig != nil {
  1032. if err := hotAPI.ApplyRoutingConfig(diff.RoutingConfig); err != nil {
  1033. logger.Info("hot apply: apply routing config failed:", err)
  1034. return false
  1035. }
  1036. }
  1037. p.SetConfig(newCfg)
  1038. return true
  1039. }
  1040. // addUserReconciling adds a user, and on an email conflict (the user was
  1041. // already applied through the runtime API) replaces the existing user instead.
  1042. func addUserReconciling(api *xray.XrayAPI, u xray.UserOp) error {
  1043. err := api.AddUser(u.Protocol, u.Tag, u.User)
  1044. if err == nil || !xray.IsUserExistsErr(err) {
  1045. return err
  1046. }
  1047. if delErr := api.RemoveUser(u.Tag, u.Email); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  1048. return delErr
  1049. }
  1050. return api.AddUser(u.Protocol, u.Tag, u.User)
  1051. }
  1052. // addInboundReconciling adds an inbound, and on a tag conflict (the handler
  1053. // was already created through the runtime API while the stored snapshot was
  1054. // stale) replaces the existing handler instead.
  1055. func addInboundReconciling(api *xray.XrayAPI, inbound []byte) error {
  1056. err := api.AddInbound(inbound)
  1057. if err == nil || !xray.IsExistingTagErr(err) {
  1058. return err
  1059. }
  1060. var meta struct {
  1061. Tag string `json:"tag"`
  1062. }
  1063. if jsonErr := json.Unmarshal(inbound, &meta); jsonErr != nil || meta.Tag == "" {
  1064. return err
  1065. }
  1066. if delErr := api.DelInbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  1067. return delErr
  1068. }
  1069. return api.AddInbound(inbound)
  1070. }
  1071. // addOutboundReconciling mirrors addInboundReconciling for outbounds.
  1072. func addOutboundReconciling(api *xray.XrayAPI, outbound []byte) error {
  1073. err := api.AddOutbound(outbound)
  1074. if err == nil || !xray.IsExistingTagErr(err) {
  1075. return err
  1076. }
  1077. var meta struct {
  1078. Tag string `json:"tag"`
  1079. }
  1080. if jsonErr := json.Unmarshal(outbound, &meta); jsonErr != nil || meta.Tag == "" {
  1081. return err
  1082. }
  1083. if delErr := api.DelOutbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  1084. return delErr
  1085. }
  1086. return api.AddOutbound(outbound)
  1087. }
  1088. // StopXray stops the running Xray process.
  1089. func (s *XrayService) StopXray() error {
  1090. lock.Lock()
  1091. defer lock.Unlock()
  1092. isManuallyStopped.Store(true)
  1093. logger.Debug("Attempting to stop Xray...")
  1094. if s.IsXrayRunning() {
  1095. return p.Stop()
  1096. }
  1097. return errors.New("xray is not running")
  1098. }
  1099. // SetToNeedRestart marks that Xray needs to be restarted.
  1100. func (s *XrayService) SetToNeedRestart() {
  1101. isNeedXrayRestart.Store(true)
  1102. }
  1103. // GetXrayAPIPort returns the port the local xray process is listening on
  1104. // for its gRPC HandlerService, or 0 when xray isn't currently running.
  1105. // Exposed for the runtime package's LocalRuntime adapter — runtime can't
  1106. // reach into the package-level `p` directly without a service-package
  1107. // import cycle.
  1108. func (s *XrayService) GetXrayAPIPort() int {
  1109. if p == nil || !p.IsRunning() {
  1110. return 0
  1111. }
  1112. return p.GetAPIPort()
  1113. }
  1114. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  1115. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  1116. return isNeedXrayRestart.CompareAndSwap(true, false)
  1117. }
  1118. // ApplyPendingRestart consumes the need-restart flag and restarts Xray. If the
  1119. // restart fails (for example GetXrayConfig hits a transient DB error and leaves
  1120. // the old process running), it re-arms the flag so the next tick retries instead
  1121. // of silently dropping the pending config change.
  1122. func (s *XrayService) ApplyPendingRestart() {
  1123. if !s.IsNeedRestartAndSetFalse() {
  1124. return
  1125. }
  1126. if err := s.RestartXray(false); err != nil {
  1127. logger.Error("restart xray failed:", err)
  1128. s.SetToNeedRestart()
  1129. }
  1130. }
  1131. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  1132. func (s *XrayService) DidXrayCrash() bool {
  1133. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  1134. }
  1135. // liftXhttpSessionIDKeys renames the legacy XHTTP session keys
  1136. // (sessionPlacement/sessionKey) to the v26.6.22 #6258 names
  1137. // (sessionIDPlacement/sessionIDKey) inside a streamSettings map. xray-core kept
  1138. // no fallback for the old names, so a config stored before the rename would be
  1139. // silently ignored by the engine. Returns true if it changed anything.
  1140. func liftXhttpSessionIDKeys(stream map[string]any) bool {
  1141. xhttp, ok := stream["xhttpSettings"].(map[string]any)
  1142. if !ok {
  1143. return false
  1144. }
  1145. changed := false
  1146. for legacy, renamed := range map[string]string{
  1147. "sessionPlacement": "sessionIDPlacement",
  1148. "sessionKey": "sessionIDKey",
  1149. } {
  1150. v, has := xhttp[legacy]
  1151. if !has {
  1152. continue
  1153. }
  1154. if _, exists := xhttp[renamed]; !exists {
  1155. xhttp[renamed] = v
  1156. }
  1157. delete(xhttp, legacy)
  1158. changed = true
  1159. }
  1160. return changed
  1161. }
  1162. // liftOutboundsXhttpSessionIDKeys applies liftXhttpSessionIDKeys to every
  1163. // outbound's streamSettings in the raw outbounds array. The original bytes are
  1164. // returned untouched when nothing needs lifting, so an unchanged config never
  1165. // looks modified to the hot-reload diff.
  1166. func liftOutboundsXhttpSessionIDKeys(raw json_util.RawMessage) json_util.RawMessage {
  1167. if len(raw) == 0 {
  1168. return raw
  1169. }
  1170. var outbounds []map[string]any
  1171. if err := json.Unmarshal(raw, &outbounds); err != nil {
  1172. return raw
  1173. }
  1174. changed := false
  1175. for _, ob := range outbounds {
  1176. if stream, ok := ob["streamSettings"].(map[string]any); ok {
  1177. if liftXhttpSessionIDKeys(stream) {
  1178. changed = true
  1179. }
  1180. }
  1181. }
  1182. if !changed {
  1183. return raw
  1184. }
  1185. if rewritten, err := json.Marshal(outbounds); err == nil {
  1186. return rewritten
  1187. }
  1188. return raw
  1189. }