xray.go 41 KB

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