1
0

xray.go 40 KB

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