xray.go 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "path"
  7. "path/filepath"
  8. "runtime"
  9. "slices"
  10. "strings"
  11. "sync"
  12. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  13. "github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
  14. "github.com/mhsanaei/3x-ui/v3/internal/config"
  15. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  16. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  17. "github.com/mhsanaei/3x-ui/v3/internal/tuic"
  18. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  19. "github.com/mhsanaei/3x-ui/v3/internal/util/maskcompat"
  20. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  21. "go.uber.org/atomic"
  22. )
  23. var (
  24. lock sync.Mutex
  25. isNeedXrayRestart atomic.Bool // Indicates that restart was requested for Xray
  26. isManuallyStopped atomic.Bool // Indicates that Xray was stopped manually from the panel
  27. xrayState xrayLifecycle
  28. )
  29. type xrayLifecycle struct {
  30. mu sync.RWMutex
  31. process *xray.Process
  32. result string
  33. // heldBack is why the running core still serves the previous config.
  34. heldBack string
  35. }
  36. func (s *xrayLifecycle) snapshot() (*xray.Process, string) {
  37. s.mu.RLock()
  38. defer s.mu.RUnlock()
  39. return s.process, s.result
  40. }
  41. func (s *xrayLifecycle) replace(process *xray.Process) {
  42. s.mu.Lock()
  43. s.process = process
  44. s.result = ""
  45. s.heldBack = ""
  46. s.mu.Unlock()
  47. }
  48. func (s *xrayLifecycle) holdBack(reason string) {
  49. s.mu.Lock()
  50. s.heldBack = reason
  51. s.mu.Unlock()
  52. }
  53. func (s *xrayLifecycle) heldBackReason() string {
  54. s.mu.RLock()
  55. defer s.mu.RUnlock()
  56. return s.heldBack
  57. }
  58. func (s *xrayLifecycle) storeResult(process *xray.Process, result string) {
  59. s.mu.Lock()
  60. if s.process == process && s.result == "" {
  61. s.result = result
  62. }
  63. s.mu.Unlock()
  64. }
  65. func currentXrayProcess() *xray.Process {
  66. process, _ := xrayState.snapshot()
  67. return process
  68. }
  69. // XrayService provides business logic for Xray process management.
  70. // It handles starting, stopping, restarting Xray, and managing its configuration.
  71. type XrayService struct {
  72. inboundService InboundService
  73. settingService SettingService
  74. nodeService NodeService
  75. xrayAPI xray.XrayAPI
  76. }
  77. // IsXrayRunning checks if the Xray process is currently running.
  78. func (s *XrayService) IsXrayRunning() bool {
  79. process := currentXrayProcess()
  80. return process != nil && process.IsRunning()
  81. }
  82. // XrayProcess returns the current Xray process instance (may be nil when Xray
  83. // is not running). It exposes the lifecycle snapshot to callers outside this
  84. // package (e.g. the tgbot subpackage).
  85. func XrayProcess() *xray.Process {
  86. return currentXrayProcess()
  87. }
  88. // GetXrayErr returns the error from the Xray process, if any.
  89. func (s *XrayService) GetXrayErr() error {
  90. process := currentXrayProcess()
  91. if process == nil {
  92. return nil
  93. }
  94. err := process.GetErr()
  95. if err == nil {
  96. return nil
  97. }
  98. if runtime.GOOS == "windows" && err.Error() == "exit status 1" {
  99. // exit status 1 on Windows means that Xray process was killed
  100. // as we kill process to stop in on Windows, this is not an error
  101. return nil
  102. }
  103. return err
  104. }
  105. // GetHeldBackConfig returns why the running core still serves its previous
  106. // config, or "" when the pending config was applied.
  107. func (s *XrayService) GetHeldBackConfig() string {
  108. return xrayState.heldBackReason()
  109. }
  110. // GetXrayResult returns the result string from the Xray process.
  111. func (s *XrayService) GetXrayResult() string {
  112. process, cachedResult := xrayState.snapshot()
  113. if cachedResult != "" {
  114. return cachedResult
  115. }
  116. if process == nil || process.IsRunning() {
  117. return ""
  118. }
  119. result := process.GetResult()
  120. if runtime.GOOS == "windows" && result == "exit status 1" {
  121. // exit status 1 on Windows means that Xray process was killed
  122. // as we kill process to stop in on Windows, this is not an error
  123. return ""
  124. }
  125. xrayState.storeResult(process, result)
  126. return result
  127. }
  128. // GetXrayVersion returns the version of the running Xray process.
  129. func (s *XrayService) GetXrayVersion() string {
  130. process := currentXrayProcess()
  131. if process == nil {
  132. return "Unknown"
  133. }
  134. return process.GetXrayVersion()
  135. }
  136. // RemoveIndex removes an element at the specified index from a slice.
  137. // Returns a new slice with the element removed.
  138. func RemoveIndex(s []any, index int) []any {
  139. return append(s[:index], s[index+1:]...)
  140. }
  141. // GetXrayConfig retrieves and builds the Xray configuration from settings and inbounds.
  142. func (s *XrayService) GetXrayConfig() (*xray.Config, error) {
  143. templateConfig, err := s.settingService.GetXrayConfigTemplate()
  144. if err != nil {
  145. return nil, err
  146. }
  147. xrayConfig := &xray.Config{}
  148. err = json.Unmarshal([]byte(templateConfig), xrayConfig)
  149. if err != nil {
  150. return nil, err
  151. }
  152. xrayConfig.LogConfig = resolveXrayLogPaths(xrayConfig.LogConfig)
  153. xrayConfig.API = ensureAPIServices(xrayConfig.API)
  154. xrayConfig.Policy = ensureStatsPolicy(xrayConfig.Policy)
  155. xrayConfig.RouterConfig = stripDisabledRules(xrayConfig.RouterConfig)
  156. // Template outbounds authored before the xray-core #6258 XHTTP rename may
  157. // still carry sessionPlacement/sessionKey; lift them too (same reason as
  158. // the per-inbound lift below).
  159. xrayConfig.OutboundConfigs = liftOutboundsXhttpSessionIDKeys(xrayConfig.OutboundConfigs)
  160. // Bridge amneziawg outbounds before anything else reads OutboundConfigs;
  161. // the core has no amneziawg proxy and would reject the raw entry.
  162. if err := transformAmneziaWGOutbounds(xrayConfig); err != nil {
  163. return nil, err
  164. }
  165. _, _, _ = s.inboundService.AddTraffic(nil, nil)
  166. inbounds, err := s.inboundService.GetAllInbounds()
  167. if err != nil {
  168. return nil, err
  169. }
  170. for _, inbound := range inbounds {
  171. if !inbound.Enable {
  172. continue
  173. }
  174. if inbound.NodeID != nil {
  175. continue
  176. }
  177. if inbound.Protocol == model.MTProto || inbound.Protocol == model.AmneziaWG || inbound.Protocol == model.TUIC {
  178. continue
  179. }
  180. settings := map[string]any{}
  181. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  182. var wireguardClientsByEmail map[string]model.Client
  183. if inbound.Protocol == model.WireGuard {
  184. inboundClients, _ := ParseInboundSettingsClients(inbound.Settings)
  185. if len(inboundClients) > 0 {
  186. wireguardClientsByEmail = make(map[string]model.Client, len(inboundClients))
  187. for _, client := range inboundClients {
  188. wireguardClientsByEmail[strings.ToLower(strings.TrimSpace(client.Email))] = client
  189. }
  190. }
  191. }
  192. dbClients, listErr := s.inboundService.clientService.ListForInbound(nil, inbound.Id)
  193. if listErr != nil {
  194. return nil, listErr
  195. }
  196. clientStats := inbound.ClientStats
  197. enableMap := make(map[string]bool, len(clientStats))
  198. for _, clientTraffic := range clientStats {
  199. enableMap[clientTraffic.Email] = clientTraffic.Enable
  200. }
  201. finalClients := make([]any, 0, len(dbClients))
  202. var wgPeers []any
  203. for i := range dbClients {
  204. c := dbClients[i]
  205. if enable, exists := enableMap[c.Email]; exists && !enable {
  206. logger.Infof("Remove Inbound User %s due to expiration or traffic limit", c.Email)
  207. continue
  208. }
  209. if !c.Enable {
  210. continue
  211. }
  212. flow := c.Flow
  213. if flow == "xtls-rprx-vision-udp443" {
  214. flow = "xtls-rprx-vision"
  215. }
  216. if inbound.DisableFlow {
  217. flow = ""
  218. }
  219. entry := map[string]any{"email": c.Email}
  220. switch inbound.Protocol {
  221. case model.VLESS:
  222. if c.ID != "" {
  223. entry["id"] = c.ID
  224. }
  225. if flow != "" {
  226. entry["flow"] = flow
  227. }
  228. if c.Reverse != nil {
  229. entry["reverse"] = c.Reverse
  230. }
  231. case model.VMESS:
  232. if c.ID != "" {
  233. entry["id"] = c.ID
  234. }
  235. if c.Security != "" {
  236. entry["security"] = c.Security
  237. }
  238. case model.Trojan:
  239. if c.Password != "" {
  240. entry["password"] = c.Password
  241. }
  242. if flow != "" {
  243. entry["flow"] = flow
  244. }
  245. case model.Shadowsocks:
  246. if c.Password != "" {
  247. entry["password"] = c.Password
  248. }
  249. case model.Hysteria:
  250. if c.Auth != "" {
  251. entry["auth"] = c.Auth
  252. }
  253. case model.WireGuard:
  254. if inboundClient, ok := wireguardClientsByEmail[strings.ToLower(strings.TrimSpace(c.Email))]; ok {
  255. c.AllowedIPs = inboundClient.AllowedIPs
  256. c.PreSharedKey = inboundClient.PreSharedKey
  257. }
  258. wgPeers = append(wgPeers, model.WireguardPeerFromClient(c))
  259. continue
  260. }
  261. finalClients = append(finalClients, entry)
  262. }
  263. var mutated bool
  264. if inbound.Protocol == model.WireGuard {
  265. delete(settings, "clients")
  266. if wgPeers == nil {
  267. wgPeers = []any{}
  268. }
  269. settings["peers"] = wgPeers
  270. mutated = true
  271. } else {
  272. _, hadClients := settings["clients"]
  273. mutated = hadClients || len(finalClients) > 0
  274. if mutated {
  275. settings["clients"] = finalClients
  276. }
  277. }
  278. if inboundCanHostFallbacks(inbound) {
  279. fallbacks, fbErr := s.inboundService.fallbackService.BuildFallbacksJSON(nil, inbound.Id)
  280. if fbErr != nil {
  281. return nil, fbErr
  282. }
  283. if len(fallbacks) > 0 {
  284. generic := make([]any, 0, len(fallbacks))
  285. for _, f := range fallbacks {
  286. generic = append(generic, f)
  287. }
  288. settings["fallbacks"] = generic
  289. mutated = true
  290. }
  291. }
  292. if mutated {
  293. modifiedSettings, err := json.MarshalIndent(settings, "", " ")
  294. if err != nil {
  295. return nil, err
  296. }
  297. inbound.Settings = string(modifiedSettings)
  298. }
  299. if len(inbound.StreamSettings) > 0 {
  300. // Unmarshal stream JSON
  301. var stream map[string]any
  302. _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  303. // Remove the "settings" field under "tlsSettings" and "realitySettings"
  304. tlsSettings, ok1 := stream["tlsSettings"].(map[string]any)
  305. realitySettings, ok2 := stream["realitySettings"].(map[string]any)
  306. if ok1 || ok2 {
  307. if ok1 {
  308. delete(tlsSettings, "settings")
  309. } else if ok2 {
  310. delete(realitySettings, "settings")
  311. }
  312. }
  313. delete(stream, "externalProxy")
  314. // finalmask.tcp + REALITY panics Xray-core on the first connection
  315. // (XTLS/Xray-core#6453). AddInbound/UpdateInbound reject this
  316. // combination at save time, but a row saved before that guard
  317. // existed (upgrade, node sync, restored backup, direct DB edit)
  318. // would still crash Xray on the next restart without this — drop
  319. // it here too, the same way liftXhttpSessionIDKeys and
  320. // HealShadowsocksClientMethods heal other legacy data in place.
  321. if len(finalMaskRealityTcpMasks(stream)) > 0 {
  322. logger.Warningf("Inbound %q: dropping finalmask, incompatible with REALITY security (crashes Xray-core, see XTLS/Xray-core#6453)", inbound.Tag)
  323. delete(stream, "finalmask")
  324. }
  325. dropEmptyRandPackets(stream["finalmask"])
  326. if dropped := stripIncompleteXmcMasks(stream); dropped > 0 {
  327. 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)
  328. }
  329. // A row that skipped the save path can still carry the pre-26.9.30 xdns lists.
  330. maskcompat.UpgradeLegacyXdns(stream["finalmask"])
  331. // xray-core v26.6.22 (#6258) renamed the XHTTP session keys and
  332. // kept no fallback. Lift legacy sessionPlacement/sessionKey onto the
  333. // new names here so inbounds stored before the rename keep working
  334. // without the admin re-saving them.
  335. liftXhttpSessionIDKeys(stream)
  336. newStream, err := json.MarshalIndent(stream, "", " ")
  337. if err != nil {
  338. return nil, err
  339. }
  340. inbound.StreamSettings = string(newStream)
  341. }
  342. if inbound.Protocol == model.Shadowsocks {
  343. if healed, ok := model.HealShadowsocksClientMethods(inbound.Settings); ok {
  344. inbound.Settings = healed
  345. }
  346. }
  347. inboundConfig := inbound.GenXrayInboundConfig()
  348. xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig)
  349. }
  350. // Merge subscription-derived outbounds (if any) into the final outbounds array.
  351. // These are additive: each subscription is placed before or after the template
  352. // outbounds based on its Prepend flag, ordered by Priority. Tags assigned by the
  353. // subscription service are kept stable across refreshes so that balancers and
  354. // routing rules continue to work.
  355. subSvc := &OutboundSubscriptionService{}
  356. if prepend, appendList, err := subSvc.activeOutboundsSplit(); err == nil && (len(prepend) > 0 || len(appendList) > 0) {
  357. mergeSubscriptionOutbounds(xrayConfig, prepend, appendList)
  358. }
  359. // Route opted-in local mtproto inbounds through the core's router. Each one
  360. // gets a loopback SOCKS bridge — tagged with the inbound's own tag so it is
  361. // matchable in routing rules — that its mtg sidecar dials Telegram through.
  362. // Done after the subscription merge so a selected subscription outbound (or
  363. // balancer) is a valid rule target.
  364. for i := range inbounds {
  365. inbound := inbounds[i]
  366. if inbound.Protocol != model.MTProto || !inbound.Enable || inbound.NodeID != nil {
  367. continue
  368. }
  369. injectMtprotoEgress(xrayConfig, inbound)
  370. }
  371. // Every AmneziaWG inbound is embedded (internal/amneziawgnet: amneziawg-go
  372. // over a gVisor netstack, no kernel module) and relays every peer's
  373. // decapsulated traffic into its own loopback SOCKS5 inbound, always on —
  374. // unlike mtproto's bridge above, there's no opt-in gate here: once
  375. // traffic is decapsulated in gVisor, Xray's own freedom outbound is the
  376. // only way it reaches the real internet at all, not an optional extra
  377. // hop. Whether it goes anywhere beyond Xray's default routing is up to
  378. // whatever rules the admin adds through the stock Routing page, exactly
  379. // like routing any other protocol.
  380. injectAmneziawgnetSocks(xrayConfig, inbounds)
  381. injectTuicSocks(xrayConfig, inbounds)
  382. // Restores each opted-in peer's own distinct public IPv6 source identity
  383. // for its outbound connections — a peer that has an IPv6 address in its
  384. // AllowedIPs, on an inbound with IPv6Enabled, gets its own freedom
  385. // outbound bound to that exact address via sendThrough.
  386. // internal/amneziawgnet's own Manager is responsible for actually
  387. // aliasing that address onto the host (see v6alias.go) so the kernel
  388. // lets Xray bind an egress socket to it at all; this call only builds
  389. // the Xray-side outbound/routing-rule half.
  390. injectAmneziawgV6Egress(xrayConfig, inbounds)
  391. // Wire the panel's own HTTP traffic through the configured outbound, after
  392. // the subscription merge so subscription outbound tags are valid targets.
  393. if egressTag, err := s.settingService.GetPanelOutbound(); err != nil {
  394. logger.Warning("read panelOutbound setting failed:", err)
  395. } else if egressTag != "" {
  396. injectPanelEgress(xrayConfig, egressTag)
  397. }
  398. nodes, err := s.nodeService.GetAll()
  399. if err != nil {
  400. logger.Warning("read nodes for egress injection failed:", err)
  401. } else {
  402. injectNodeEgresses(xrayConfig, nodes)
  403. }
  404. return xrayConfig, nil
  405. }
  406. // PanelEgressInboundTag is the tag of the loopback SOCKS inbound injected into
  407. // the generated config when a panel outbound is configured. The panel's own
  408. // HTTP clients dial through it to egress via the chosen outbound.
  409. const PanelEgressInboundTag = "panel-egress"
  410. // panelEgressBasePort is the first port tried for the egress bridge; ports
  411. // already taken by other inbounds in the generated config are skipped.
  412. const panelEgressBasePort = 62790
  413. // injectPanelEgress appends a loopback SOCKS inbound and routing rule only when
  414. // outboundTag resolves in the final outbound or balancer set. Otherwise the
  415. // entire injection is skipped. Generated state is hot-appliable and never
  416. // modifies the stored template or restarts the core.
  417. func injectPanelEgress(cfg *xray.Config, outboundTag string) {
  418. for i := range cfg.InboundConfigs {
  419. if cfg.InboundConfigs[i].Tag == PanelEgressInboundTag {
  420. logger.Warning("panel egress: inbound tag [", PanelEgressInboundTag, "] already exists, skipping injection")
  421. return
  422. }
  423. }
  424. // The rule must exist before the inbound takes traffic, otherwise the
  425. // bridge would silently egress through the default outbound instead.
  426. routing := map[string]any{}
  427. if len(cfg.RouterConfig) > 0 {
  428. if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
  429. logger.Warning("panel egress: routing section is unparsable, skipping injection:", err)
  430. return
  431. }
  432. }
  433. if !routingTargetExists(routing, cfg.OutboundConfigs, outboundTag) {
  434. logger.Warning("panel egress: target tag [", outboundTag, "] not found, skipping injection")
  435. return
  436. }
  437. rules, _ := routing["rules"].([]any)
  438. rule := map[string]any{
  439. "type": "field",
  440. "inboundTag": []any{PanelEgressInboundTag},
  441. }
  442. // The configured tag may name a routing balancer instead of a concrete
  443. // outbound. A field rule can target either, so emit the matching key —
  444. // balancerTag load-balances the panel's own traffic across the balancer's
  445. // outbounds, while a plain outbound tag keeps the original behavior.
  446. if routingTagIsBalancer(routing, outboundTag) {
  447. rule["balancerTag"] = outboundTag
  448. } else {
  449. rule["outboundTag"] = outboundTag
  450. }
  451. routing["rules"] = append([]any{rule}, rules...)
  452. newRouting, err := json.Marshal(routing)
  453. if err != nil {
  454. logger.Warning("panel egress: failed to rebuild routing section, skipping injection:", err)
  455. return
  456. }
  457. cfg.RouterConfig = json_util.RawMessage(newRouting)
  458. used := make(map[int]struct{}, len(cfg.InboundConfigs))
  459. for i := range cfg.InboundConfigs {
  460. used[cfg.InboundConfigs[i].Port] = struct{}{}
  461. }
  462. port := panelEgressBasePort
  463. for {
  464. if _, taken := used[port]; !taken {
  465. break
  466. }
  467. port++
  468. }
  469. cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
  470. Listen: json_util.RawMessage(`"127.0.0.1"`),
  471. Port: port,
  472. Protocol: "socks",
  473. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  474. Tag: PanelEgressInboundTag,
  475. })
  476. }
  477. func outboundTagExists(outbounds json_util.RawMessage, tag string) bool {
  478. var parsed []struct {
  479. Tag string `json:"tag"`
  480. }
  481. if tag == "" || json.Unmarshal(outbounds, &parsed) != nil {
  482. return false
  483. }
  484. for _, outbound := range parsed {
  485. if outbound.Tag == tag {
  486. return true
  487. }
  488. }
  489. return false
  490. }
  491. func routingTargetExists(routing map[string]any, outbounds json_util.RawMessage, tag string) bool {
  492. return routingTagIsBalancer(routing, tag) || outboundTagExists(outbounds, tag)
  493. }
  494. // NodeEgressInboundTag returns the loopback SOCKS inbound tag for a given node.
  495. func NodeEgressInboundTag(nodeID int) string {
  496. return fmt.Sprintf("node-egress-%d", nodeID)
  497. }
  498. // nodeEgressBasePort is the first port tried for node egress bridges.
  499. const nodeEgressBasePort = 62800
  500. // injectNodeEgresses appends a loopback SOCKS inbound per enabled node that has
  501. // an OutboundTag, and prepends a routing rule sending that inbound's traffic to
  502. // the selected outbound tag. These bridges are hot-appliable.
  503. func injectNodeEgresses(cfg *xray.Config, nodes []*model.Node) {
  504. routing := map[string]any{}
  505. if len(cfg.RouterConfig) > 0 {
  506. if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
  507. logger.Warning("node egress: routing section is unparsable, skipping injection:", err)
  508. return
  509. }
  510. }
  511. used := make(map[int]struct{}, len(cfg.InboundConfigs))
  512. usedTags := make(map[string]struct{}, len(cfg.InboundConfigs))
  513. for i := range cfg.InboundConfigs {
  514. used[cfg.InboundConfigs[i].Port] = struct{}{}
  515. usedTags[cfg.InboundConfigs[i].Tag] = struct{}{}
  516. }
  517. rules, _ := routing["rules"].([]any)
  518. newRules := make([]any, 0)
  519. for _, n := range nodes {
  520. if !n.Enable || n.OutboundTag == "" {
  521. continue
  522. }
  523. if !routingTargetExists(routing, cfg.OutboundConfigs, n.OutboundTag) {
  524. logger.Warning("node egress: target tag [", n.OutboundTag, "] not found, skipping node [", n.Id, "]")
  525. continue
  526. }
  527. tag := NodeEgressInboundTag(n.Id)
  528. if _, exists := usedTags[tag]; exists {
  529. logger.Warning("node egress: inbound tag [", tag, "] already exists, skipping")
  530. continue
  531. }
  532. usedTags[tag] = struct{}{}
  533. rule := map[string]any{
  534. "type": "field",
  535. "inboundTag": []any{tag},
  536. }
  537. if routingTagIsBalancer(routing, n.OutboundTag) {
  538. rule["balancerTag"] = n.OutboundTag
  539. } else {
  540. rule["outboundTag"] = n.OutboundTag
  541. }
  542. newRules = append(newRules, rule)
  543. port := nodeEgressBasePort + n.Id
  544. for {
  545. if _, taken := used[port]; !taken {
  546. break
  547. }
  548. port++
  549. }
  550. used[port] = struct{}{}
  551. cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
  552. Listen: json_util.RawMessage(`"127.0.0.1"`),
  553. Port: port,
  554. Protocol: "socks",
  555. Settings: json_util.RawMessage(`{"auth":"noauth","udp":false}`),
  556. Tag: tag,
  557. })
  558. }
  559. if len(newRules) == 0 {
  560. return
  561. }
  562. routing["rules"] = append(newRules, rules...)
  563. newRouting, err := json.Marshal(routing)
  564. if err != nil {
  565. logger.Warning("node egress: failed to rebuild routing section, skipping injection:", err)
  566. return
  567. }
  568. cfg.RouterConfig = json_util.RawMessage(newRouting)
  569. }
  570. // routingTagIsBalancer reports whether tag names a balancer in the parsed
  571. // routing section. The panel-egress rule targets a balancer via balancerTag and
  572. // a concrete outbound via outboundTag, so the caller picks the key from this.
  573. func routingTagIsBalancer(routing map[string]any, tag string) bool {
  574. if tag == "" {
  575. return false
  576. }
  577. balancers, ok := routing["balancers"].([]any)
  578. if !ok {
  579. return false
  580. }
  581. for _, b := range balancers {
  582. bm, ok := b.(map[string]any)
  583. if !ok {
  584. continue
  585. }
  586. if t, ok := bm["tag"].(string); ok && t == tag {
  587. return true
  588. }
  589. }
  590. return false
  591. }
  592. // mtprotoEgressSocksSettings is the loopback SOCKS server a routed mtproto
  593. // inbound exposes for its mtg sidecar to dial Telegram through. mtg makes plain
  594. // TCP connections, so UDP is left off (matching the panel egress bridge).
  595. const mtprotoEgressSocksSettings = `{"auth":"noauth","udp":false}`
  596. // injectMtprotoEgress wires one routed mtproto inbound into the generated
  597. // config after any selected outbound resolves in the final target set. Invalid
  598. // selected targets or routing data skip the entire injection; without a selected
  599. // outbound, the bridge retains default-route behavior. Generated state remains
  600. // hot-appliable, leaves the stored template untouched, and never forces a full
  601. // Xray restart. Mirrors injectPanelEgress.
  602. func injectMtprotoEgress(cfg *xray.Config, inbound *model.Inbound) {
  603. var parsed struct {
  604. RouteThroughXray bool `json:"routeThroughXray"`
  605. RouteXrayPort int `json:"routeXrayPort"`
  606. OutboundTag string `json:"outboundTag"`
  607. }
  608. if err := json.Unmarshal([]byte(inbound.Settings), &parsed); err != nil {
  609. return
  610. }
  611. if !parsed.RouteThroughXray || parsed.RouteXrayPort <= 0 || inbound.Tag == "" {
  612. return
  613. }
  614. tag := inbound.Tag
  615. for i := range cfg.InboundConfigs {
  616. if cfg.InboundConfigs[i].Tag == tag {
  617. logger.Warning("mtproto egress: inbound tag [", tag, "] already present in generated config, skipping bridge")
  618. return
  619. }
  620. }
  621. if parsed.OutboundTag != "" {
  622. routing := map[string]any{}
  623. if len(cfg.RouterConfig) > 0 {
  624. if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
  625. logger.Warning("mtproto egress: routing section is unparsable, skipping injection:", err)
  626. return
  627. }
  628. }
  629. if !routingTargetExists(routing, cfg.OutboundConfigs, parsed.OutboundTag) {
  630. logger.Warning("mtproto egress: target tag [", parsed.OutboundTag, "] not found, skipping injection")
  631. return
  632. }
  633. rules, _ := routing["rules"].([]any)
  634. rule := map[string]any{
  635. "type": "field",
  636. "inboundTag": []any{tag},
  637. }
  638. if routingTagIsBalancer(routing, parsed.OutboundTag) {
  639. rule["balancerTag"] = parsed.OutboundTag
  640. } else {
  641. rule["outboundTag"] = parsed.OutboundTag
  642. }
  643. routing["rules"] = append([]any{rule}, rules...)
  644. newRouting, err := json.Marshal(routing)
  645. if err != nil {
  646. logger.Warning("mtproto egress: failed to rebuild routing section, skipping injection:", err)
  647. return
  648. }
  649. cfg.RouterConfig = json_util.RawMessage(newRouting)
  650. }
  651. cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
  652. Listen: json_util.RawMessage(`"127.0.0.1"`),
  653. Port: parsed.RouteXrayPort,
  654. Protocol: "socks",
  655. Settings: json_util.RawMessage(mtprotoEgressSocksSettings),
  656. Tag: tag,
  657. })
  658. }
  659. // Peers resolve DNS inside the tunnel, so domain rules match only via sniffing; routeOnly
  660. // keeps the dial on the peer's IP, else Telegram's FakeTLS (IP + foreign SNI) breaks.
  661. const amneziawgEgressSniffingSettings = `{"enabled":true,"destOverride":["http","tls","quic","fakedns"],"routeOnly":true}`
  662. // injectAmneziawgnetSocks gives every enabled AmneziaWG inbound with at
  663. // least one qualifying peer its own loopback SOCKS5 inbound for the
  664. // embedded (amneziawg-go) relay path (internal/amneziawgnet) -- always on,
  665. // since there is no alternative datapath once traffic is decapsulated in
  666. // gVisor: Xray's own freedom outbound is how it reaches the real internet at
  667. // all (see internal/amneziawgnet/relay.go's doc comment, Finding 3 of the
  668. // migration plan). Tagged with the inbound's own real tag: it's already
  669. // selectable in the panel's stock Routing page (InboundService.GetInboundTags
  670. // is protocol-blind), and per-inbound traffic totals
  671. // (internal/web/service/inbound_traffic.go's addClientTraffic) match by
  672. // exact tag -- reusing it isn't a style choice.
  673. func injectAmneziawgnetSocks(cfg *xray.Config, inbounds []*model.Inbound) {
  674. existingTags := make(map[string]struct{}, len(cfg.InboundConfigs))
  675. for i := range cfg.InboundConfigs {
  676. existingTags[cfg.InboundConfigs[i].Tag] = struct{}{}
  677. }
  678. for _, inbound := range inbounds {
  679. if inbound.Protocol != model.AmneziaWG || !inbound.Enable || inbound.NodeID != nil {
  680. continue
  681. }
  682. inst, ok := amneziawg.InstanceFromInbound(inbound)
  683. if !ok {
  684. continue
  685. }
  686. if _, taken := existingTags[inbound.Tag]; taken {
  687. logger.Warning("amneziawgnet socks: inbound tag [", inbound.Tag, "] already present in generated config, skipping its relay inbound")
  688. continue
  689. }
  690. emails := make([]string, 0, len(inst.Peers))
  691. for _, p := range inst.Peers {
  692. if p.Email != "" {
  693. emails = append(emails, p.Email)
  694. }
  695. }
  696. if len(emails) == 0 {
  697. continue
  698. }
  699. settings, err := amneziawgnet.SocksInboundSettings(emails, amneziawgnet.SocksPassword())
  700. if err != nil {
  701. logger.Warning("amneziawgnet socks: building settings for inbound [", inbound.Tag, "]: ", err)
  702. continue
  703. }
  704. existingTags[inbound.Tag] = struct{}{}
  705. cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
  706. Listen: json_util.RawMessage(`"127.0.0.1"`),
  707. Port: amneziawgnet.SOCKSPortForInbound(inbound.Id),
  708. Protocol: "socks",
  709. Settings: json_util.RawMessage(settings),
  710. Sniffing: json_util.RawMessage(amneziawgEgressSniffingSettings),
  711. Tag: inbound.Tag,
  712. })
  713. }
  714. }
  715. const (
  716. tuicEgressSocksSettings = `{"auth":"noauth","udp":true}`
  717. tuicEgressSniffingSettings = `{"enabled":true,"destOverride":["http","tls","quic","fakedns"]}`
  718. )
  719. func injectTuicSocks(cfg *xray.Config, inbounds []*model.Inbound) {
  720. existingTags := make(map[string]struct{}, len(cfg.InboundConfigs))
  721. for i := range cfg.InboundConfigs {
  722. existingTags[cfg.InboundConfigs[i].Tag] = struct{}{}
  723. }
  724. for _, inbound := range inbounds {
  725. if inbound.Protocol != model.TUIC || !inbound.Enable || inbound.NodeID != nil {
  726. continue
  727. }
  728. if _, taken := existingTags[inbound.Tag]; taken {
  729. logger.Warning("tuic socks: inbound tag [", inbound.Tag, "] already present in generated config, skipping its relay inbound")
  730. continue
  731. }
  732. existingTags[inbound.Tag] = struct{}{}
  733. cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
  734. Listen: json_util.RawMessage(`"127.0.0.1"`),
  735. Port: tuic.SOCKSPortForInbound(inbound.Id),
  736. Protocol: "socks",
  737. Settings: json_util.RawMessage(tuicEgressSocksSettings),
  738. Sniffing: json_util.RawMessage(tuicEgressSniffingSettings),
  739. Tag: inbound.Tag,
  740. })
  741. }
  742. }
  743. // amneziawgV6EgressTag returns the stable, globally-unique freedom outbound
  744. // tag for one peer's IPv6 source-identity egress. Stable across config
  745. // regenerations (a pure function of two stable identifiers), so
  746. // internal/xray/hot_diff.go's tag-keyed outbound/routing diffing recognizes
  747. // "unchanged" rather than remove+recreate on every poll. The inbound.Id
  748. // prefix is defense in depth, not load-bearing on its own: email is already
  749. // enforced globally unique across the whole panel's client table
  750. // (model.ClientRecord.Email has a gorm uniqueIndex) — kept anyway since it
  751. // costs nothing and makes the tag self-describing, matching
  752. // NodeEgressInboundTag's own style.
  753. func amneziawgV6EgressTag(inboundID int, email string) string {
  754. return fmt.Sprintf("amneziawg-v6-%d-%s", inboundID, email)
  755. }
  756. // injectAmneziawgV6Egress gives every enabled, non-node-hosted AmneziaWG
  757. // peer with an IPv6 AllowedIPs entry its own single-purpose freedom
  758. // outbound, bound via sendThrough to that exact address, plus a routing
  759. // rule sending only that peer's IPv6-destined traffic through it — restoring the
  760. // per-client public IPv6 identity the hard cutover temporarily dropped
  761. // (Phase 3.5 of the migration plan). Scoped to outbound source identity
  762. // only: it depends on internal/amneziawgnet's own alias mechanism actually
  763. // giving the host that address at the OS level (see v6alias.go's
  764. // V6AliasesActive, the exact same gate this function uses below) — without
  765. // that, sendThrough fails to bind and every connection through it errors
  766. // outright (freedom.go's dial failure); there is no fallback outbound.
  767. //
  768. // The routing rule matches both inboundTag and user: SocksInboundSettings
  769. // (used by injectAmneziawgnetSocks above) already authenticates each
  770. // connection as the peer's own email via stock SOCKS5 auth, and a stock
  771. // Xray SOCKS5 inbound sets that connection's stats/routing identity from
  772. // the authenticated username — so "user" reliably isolates exactly one
  773. // peer's traffic, the same building block Finding 3 of the migration plan
  774. // already established for per-client stats.
  775. //
  776. // Modeled on injectNodeEgresses (the established N-per-slice inbound+rule
  777. // precedent, not injectAmneziawgnetSocks itself, which only ever emits a
  778. // single inbound and never touches outbounds/routing) and
  779. // mergeSubscriptionOutbounds's unmarshal-append-remarshal pattern for
  780. // cfg.OutboundConfigs. Synthetic rules are prepended ahead of whatever's
  781. // already in the routing rules array, the same pattern injectNodeEgresses/
  782. // injectMtprotoEgress already use for their own always-must-win infra
  783. // rules — this never touches the admin's own saved Routing-page rule
  784. // order.
  785. func injectAmneziawgV6Egress(cfg *xray.Config, inbounds []*model.Inbound) {
  786. // Protocol is checked alongside Tag, not just Tag alone: a tag collision
  787. // with some unrelated (non-socks) inbound must not be mistaken for this
  788. // instance's own relay having been created.
  789. liveInboundTags := make(map[string]struct{}, len(cfg.InboundConfigs))
  790. for i := range cfg.InboundConfigs {
  791. if cfg.InboundConfigs[i].Protocol == "socks" {
  792. liveInboundTags[cfg.InboundConfigs[i].Tag] = struct{}{}
  793. }
  794. }
  795. var existingOutbounds []any
  796. if len(cfg.OutboundConfigs) > 0 {
  797. if err := json.Unmarshal(cfg.OutboundConfigs, &existingOutbounds); err != nil {
  798. logger.Warning("amneziawg v6 egress: outbounds section is unparsable, skipping injection:", err)
  799. return
  800. }
  801. }
  802. usedOutboundTags := make(map[string]struct{}, len(existingOutbounds))
  803. for _, o := range existingOutbounds {
  804. if m, ok := o.(map[string]any); ok {
  805. if t, ok := m["tag"].(string); ok {
  806. usedOutboundTags[t] = struct{}{}
  807. }
  808. }
  809. }
  810. routing := map[string]any{}
  811. if len(cfg.RouterConfig) > 0 {
  812. if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
  813. logger.Warning("amneziawg v6 egress: routing section is unparsable, skipping injection:", err)
  814. return
  815. }
  816. }
  817. rules, _ := routing["rules"].([]any)
  818. newRules := make([]any, 0)
  819. newOutbounds := make([]any, 0)
  820. for _, inbound := range inbounds {
  821. if inbound.Protocol != model.AmneziaWG || !inbound.Enable || inbound.NodeID != nil {
  822. continue
  823. }
  824. if _, live := liveInboundTags[inbound.Tag]; !live {
  825. // The relay inbound itself wasn't created this pass (e.g. a tag
  826. // collision inside injectAmneziawgnetSocks) -- no SOCKS5 inbound
  827. // exists for hot_diff.go's inboundTag match to ever fire against.
  828. continue
  829. }
  830. inst, ok := amneziawg.InstanceFromInbound(inbound)
  831. if !ok || !amneziawgnet.V6AliasesActive(inst) {
  832. continue
  833. }
  834. for _, p := range inst.Peers {
  835. if p.Email == "" {
  836. continue
  837. }
  838. v6 := amneziawg.FirstIPv6(p.AllowedIPs)
  839. if v6 == "" {
  840. continue
  841. }
  842. tag := amneziawgV6EgressTag(inbound.Id, p.Email)
  843. if _, taken := usedOutboundTags[tag]; taken {
  844. logger.Warning("amneziawg v6 egress: outbound tag [", tag, "] already exists, skipping peer [", p.Email, "]")
  845. continue
  846. }
  847. usedOutboundTags[tag] = struct{}{}
  848. newOutbounds = append(newOutbounds, map[string]any{
  849. "tag": tag,
  850. "protocol": "freedom",
  851. "sendThrough": v6,
  852. "settings": map[string]any{},
  853. })
  854. newRules = append(newRules, map[string]any{
  855. "type": "field",
  856. "inboundTag": []any{inbound.Tag},
  857. "user": []any{p.Email},
  858. "ip": []any{"::/0"},
  859. "outboundTag": tag,
  860. })
  861. }
  862. }
  863. if len(newOutbounds) == 0 {
  864. return
  865. }
  866. merged := make([]any, 0, len(existingOutbounds))
  867. merged = append(merged, existingOutbounds...)
  868. merged = append(merged, newOutbounds...)
  869. combined, err := json.MarshalIndent(merged, "", " ")
  870. if err != nil {
  871. logger.Warning("amneziawg v6 egress: failed to rebuild outbounds section, skipping injection:", err)
  872. return
  873. }
  874. cfg.OutboundConfigs = json_util.RawMessage(combined)
  875. routing["rules"] = append(newRules, rules...)
  876. newRouting, err := json.Marshal(routing)
  877. if err != nil {
  878. logger.Warning("amneziawg v6 egress: failed to rebuild routing section, skipping injection:", err)
  879. return
  880. }
  881. cfg.RouterConfig = json_util.RawMessage(newRouting)
  882. }
  883. // mergeSubscriptionOutbounds appends the subscription outbounds to the
  884. // OutboundConfigs array of the xray config. It works on the already-unmarshaled
  885. // template so that manually configured outbounds are never overwritten.
  886. //
  887. // Safety: if we cannot parse the template's outbounds array, we leave
  888. // OutboundConfigs exactly as it came from the template (we do not inject
  889. // subscription outbounds). This prevents us from accidentally dropping the
  890. // user's manually configured outbounds when the template is in a weird state.
  891. func mergeSubscriptionOutbounds(cfg *xray.Config, prepend, appendList []any) {
  892. if len(prepend) == 0 && len(appendList) == 0 {
  893. return
  894. }
  895. var templateOutbounds []any
  896. if len(cfg.OutboundConfigs) > 0 {
  897. if err := json.Unmarshal(cfg.OutboundConfigs, &templateOutbounds); err != nil {
  898. // Corrupt template outbounds — do not touch the field at all.
  899. // The user will see problems on Xray start / next save.
  900. return
  901. }
  902. }
  903. var merged []any
  904. merged = append(merged, prepend...)
  905. merged = append(merged, templateOutbounds...)
  906. merged = append(merged, appendList...)
  907. combined, err := json.MarshalIndent(merged, "", " ")
  908. if err != nil {
  909. return
  910. }
  911. cfg.OutboundConfigs = json_util.RawMessage(combined)
  912. }
  913. // ensureAPIServices guarantees the gRPC services the panel depends on are
  914. // listed in the generated config's api block: HandlerService and StatsService
  915. // have always been required for inbound/user management and traffic polling,
  916. // and RoutingService enables hot routing reload on templates saved before it
  917. // was added to the default template. The stored template itself is not
  918. // modified — only the generated runtime config.
  919. func ensureAPIServices(api json_util.RawMessage) json_util.RawMessage {
  920. if len(api) == 0 {
  921. // No api block means the panel's API integration is deliberately
  922. // disabled; don't resurrect it behind the user's back.
  923. return api
  924. }
  925. var parsed map[string]any
  926. if err := json.Unmarshal(api, &parsed); err != nil {
  927. return api
  928. }
  929. services, _ := parsed["services"].([]any)
  930. have := make(map[string]bool, len(services))
  931. for _, svc := range services {
  932. if name, ok := svc.(string); ok {
  933. have[name] = true
  934. }
  935. }
  936. added := false
  937. for _, name := range []string{"HandlerService", "StatsService", "RoutingService"} {
  938. if !have[name] {
  939. services = append(services, name)
  940. added = true
  941. }
  942. }
  943. if !added {
  944. return api
  945. }
  946. parsed["services"] = services
  947. out, err := json.Marshal(parsed)
  948. if err != nil {
  949. return api
  950. }
  951. return out
  952. }
  953. // ensureStatsPolicy guarantees every policy level in the generated config has
  954. // statsUserOnline enabled, so the core tracks per-email online IPs for the
  955. // panel's online view and access-log-free IP limiting. Generated clients carry
  956. // no explicit level, so level "0" is created when absent. The flag is panel
  957. // infrastructure and is forced on even over an explicit false in the template,
  958. // same as the api services above. An entirely missing or unparsable policy
  959. // block is left alone; the stored template itself is never modified — only the
  960. // generated runtime config.
  961. func ensureStatsPolicy(policy json_util.RawMessage) json_util.RawMessage {
  962. if len(policy) == 0 {
  963. return policy
  964. }
  965. var parsed map[string]any
  966. if err := json.Unmarshal(policy, &parsed); err != nil {
  967. return policy
  968. }
  969. levels, _ := parsed["levels"].(map[string]any)
  970. if levels == nil {
  971. levels = make(map[string]any)
  972. }
  973. if _, ok := levels["0"]; !ok {
  974. levels["0"] = map[string]any{}
  975. }
  976. changed := false
  977. for _, raw := range levels {
  978. level, ok := raw.(map[string]any)
  979. if !ok {
  980. continue
  981. }
  982. if enabled, ok := level["statsUserOnline"].(bool); !ok || !enabled {
  983. level["statsUserOnline"] = true
  984. changed = true
  985. }
  986. }
  987. if !changed {
  988. return policy
  989. }
  990. parsed["levels"] = levels
  991. out, err := json.Marshal(parsed)
  992. if err != nil {
  993. return policy
  994. }
  995. return out
  996. }
  997. // caseVariantKeys returns every key of parsed that equals want ignoring case,
  998. // lowest first so the fold is deterministic when several variants are present.
  999. func caseVariantKeys(parsed map[string]any, want string) []string {
  1000. var keys []string
  1001. for key := range parsed {
  1002. if strings.EqualFold(key, want) {
  1003. keys = append(keys, key)
  1004. }
  1005. }
  1006. slices.Sort(keys)
  1007. return keys
  1008. }
  1009. func resolveXrayLogPaths(logCfg json_util.RawMessage) json_util.RawMessage {
  1010. if len(logCfg) == 0 {
  1011. return logCfg
  1012. }
  1013. var parsed map[string]any
  1014. if err := json.Unmarshal(logCfg, &parsed); err != nil {
  1015. return logCfg
  1016. }
  1017. changed := false
  1018. for _, key := range []string{"access", "error"} {
  1019. // xray-core decodes this object with encoding/json, whose case-insensitive
  1020. // field match makes "Access" reach AccessLog too — fold every variant.
  1021. variants := caseVariantKeys(parsed, key)
  1022. value, hasValue := parsed[key]
  1023. for _, variant := range variants {
  1024. if variant == key {
  1025. continue
  1026. }
  1027. if !hasValue {
  1028. value, hasValue = parsed[variant], true
  1029. }
  1030. delete(parsed, variant)
  1031. changed = true
  1032. }
  1033. v, ok := value.(string)
  1034. if !ok {
  1035. continue
  1036. }
  1037. trimmed := strings.TrimSpace(v)
  1038. if trimmed == "" || strings.EqualFold(trimmed, "none") {
  1039. if changed {
  1040. parsed[key] = v
  1041. }
  1042. continue
  1043. }
  1044. base := path.Base(filepath.ToSlash(trimmed))
  1045. if base == "" || base == "." || base == ".." || base == "/" {
  1046. continue
  1047. }
  1048. confined := filepath.Join(config.GetLogFolder(), base)
  1049. if confined == trimmed {
  1050. continue
  1051. }
  1052. parsed[key] = confined
  1053. changed = true
  1054. }
  1055. if !changed {
  1056. return logCfg
  1057. }
  1058. out, err := json.Marshal(parsed)
  1059. if err != nil {
  1060. return logCfg
  1061. }
  1062. return out
  1063. }
  1064. // stripDisabledRules removes routing rules marked `enabled: false` from the
  1065. // generated runtime config and strips panel-only keys (`enabled`, `comment`)
  1066. // from the rest, since xray-core has no such fields. The internal api rule is
  1067. // always kept (see isApiRule) so traffic stats can't be toggled off. The stored
  1068. // template is untouched — only the generated config is filtered.
  1069. func stripDisabledRules(routerCfg json_util.RawMessage) json_util.RawMessage {
  1070. if len(routerCfg) == 0 {
  1071. return routerCfg
  1072. }
  1073. var parsed map[string]any
  1074. if err := json.Unmarshal(routerCfg, &parsed); err != nil {
  1075. return routerCfg
  1076. }
  1077. rules, ok := parsed["rules"].([]any)
  1078. if !ok || len(rules) == 0 {
  1079. return routerCfg
  1080. }
  1081. var activeRules []any
  1082. changed := false
  1083. for _, rawRule := range rules {
  1084. rule, ok := rawRule.(map[string]any)
  1085. if !ok {
  1086. activeRules = append(activeRules, rawRule)
  1087. continue
  1088. }
  1089. if enabledRaw, exists := rule["enabled"]; exists {
  1090. // The internal api rule carries traffic stats and must never be
  1091. // dropped, even if it was somehow marked disabled.
  1092. enabled, ok := enabledRaw.(bool)
  1093. if ok && !enabled && !isApiRule(rule) {
  1094. changed = true
  1095. continue
  1096. }
  1097. delete(rule, "enabled")
  1098. changed = true
  1099. }
  1100. if _, exists := rule["comment"]; exists {
  1101. delete(rule, "comment")
  1102. changed = true
  1103. }
  1104. activeRules = append(activeRules, rule)
  1105. }
  1106. if !changed {
  1107. return routerCfg
  1108. }
  1109. parsed["rules"] = activeRules
  1110. out, err := json.Marshal(parsed)
  1111. if err != nil {
  1112. return routerCfg
  1113. }
  1114. return out
  1115. }
  1116. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  1117. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  1118. process := currentXrayProcess()
  1119. if process == nil || !process.IsRunning() {
  1120. err := errors.New("xray is not running")
  1121. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  1122. return nil, nil, err
  1123. }
  1124. apiPort := process.GetAPIPort()
  1125. if err := s.xrayAPI.Init(apiPort); err != nil {
  1126. logger.Debug("Failed to initialize Xray API:", err)
  1127. return nil, nil, err
  1128. }
  1129. defer s.xrayAPI.Close()
  1130. traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
  1131. if err != nil {
  1132. logger.Debug("Failed to fetch Xray traffic:", err)
  1133. return nil, nil, err
  1134. }
  1135. return traffic, clientTraffic, nil
  1136. }
  1137. // GetOnlineUsers returns connection-based online users (email + source IPs)
  1138. // from the running core's online-stats API. ok=false means the API is not
  1139. // available — xray isn't running or the core predates the online-stats RPCs —
  1140. // and callers must use the legacy traffic-delta / access-log paths. The
  1141. // capability is probed lazily per process: an Unimplemented answer pins this
  1142. // core as unsupported until the next restart, while transient errors leave the
  1143. // capability undecided so a flaky poll can't lock in legacy mode.
  1144. func (s *XrayService) GetOnlineUsers() ([]xray.OnlineUser, bool, error) {
  1145. process := currentXrayProcess()
  1146. if process == nil || !process.IsRunning() {
  1147. return nil, false, nil
  1148. }
  1149. if process.OnlineAPISupport() == xray.OnlineAPIUnsupported {
  1150. return nil, false, nil
  1151. }
  1152. if err := s.xrayAPI.Init(process.GetAPIPort()); err != nil {
  1153. logger.Debug("Failed to initialize Xray API:", err)
  1154. return nil, false, err
  1155. }
  1156. defer s.xrayAPI.Close()
  1157. users, err := s.xrayAPI.GetOnlineUsers()
  1158. if err != nil {
  1159. if xray.IsUnimplementedErr(err) {
  1160. process.SetOnlineAPISupport(xray.OnlineAPIUnsupported)
  1161. logger.Info("xray core does not support the online-stats API; falling back to traffic-delta onlines and access-log IP limit")
  1162. return nil, false, nil
  1163. }
  1164. logger.Debug("Failed to fetch Xray online users:", err)
  1165. return nil, false, err
  1166. }
  1167. if process.OnlineAPISupport() == xray.OnlineAPIUnknown {
  1168. process.SetOnlineAPISupport(xray.OnlineAPISupported)
  1169. logger.Info("xray core supports the online-stats API; using connection-based onlines and access-log-free IP limit")
  1170. }
  1171. return users, true, nil
  1172. }
  1173. // BalancerStatus is the live view of one balancer for the panel UI. Running
  1174. // is false when the balancer isn't present in the running core (e.g. xray is
  1175. // stopped or the balancer hasn't been saved/applied yet).
  1176. type BalancerStatus struct {
  1177. Tag string `json:"tag"`
  1178. Running bool `json:"running"`
  1179. Override string `json:"override"`
  1180. Selected []string `json:"selected"`
  1181. }
  1182. // GetBalancersStatus queries the running core for the live state of the
  1183. // given balancer tags. Per-tag failures are reported as Running=false rather
  1184. // than failing the whole call, so the UI can render saved-but-not-applied
  1185. // balancers alongside live ones.
  1186. func (s *XrayService) GetBalancersStatus(tags []string) ([]BalancerStatus, error) {
  1187. statuses := make([]BalancerStatus, 0, len(tags))
  1188. process := currentXrayProcess()
  1189. if process == nil || !process.IsRunning() {
  1190. for _, tag := range tags {
  1191. statuses = append(statuses, BalancerStatus{Tag: tag})
  1192. }
  1193. return statuses, nil
  1194. }
  1195. if err := s.xrayAPI.Init(process.GetAPIPort()); err != nil {
  1196. return nil, err
  1197. }
  1198. defer s.xrayAPI.Close()
  1199. for _, tag := range tags {
  1200. info, err := s.xrayAPI.GetBalancerInfo(tag)
  1201. if err != nil {
  1202. logger.Debug("get balancer info [", tag, "] failed:", err)
  1203. statuses = append(statuses, BalancerStatus{Tag: tag})
  1204. continue
  1205. }
  1206. statuses = append(statuses, BalancerStatus{
  1207. Tag: tag,
  1208. Running: true,
  1209. Override: info.Override,
  1210. Selected: info.Selected,
  1211. })
  1212. }
  1213. return statuses, nil
  1214. }
  1215. // OverrideBalancer forces a balancer in the running core to use the given
  1216. // outbound tag; an empty target clears the override. When target names
  1217. // another balancer, the override resolves to the loopback outbound that
  1218. // routes traffic through the target balancer via the routing rules.
  1219. func (s *XrayService) OverrideBalancer(tag, target string) error {
  1220. process := currentXrayProcess()
  1221. if process == nil || !process.IsRunning() {
  1222. return errors.New("xray is not running")
  1223. }
  1224. if target != "" {
  1225. resolved, err := s.resolveOverrideTarget(target)
  1226. if err != nil {
  1227. return err
  1228. }
  1229. if resolved != "" {
  1230. target = resolved
  1231. }
  1232. }
  1233. if err := s.xrayAPI.Init(process.GetAPIPort()); err != nil {
  1234. return err
  1235. }
  1236. defer s.xrayAPI.Close()
  1237. return s.xrayAPI.SetBalancerTarget(tag, target)
  1238. }
  1239. // resolveOverrideTarget checks if target names a balancer and, if so,
  1240. // returns the loopback outbound tag that routes to it through the
  1241. // routing rules. Returns empty if target is already a concrete outbound.
  1242. func (s *XrayService) resolveOverrideTarget(target string) (string, error) {
  1243. template, err := s.settingService.GetXrayConfigTemplate()
  1244. if err != nil {
  1245. return "", err
  1246. }
  1247. var cfg map[string]any
  1248. if err := json.Unmarshal([]byte(template), &cfg); err != nil {
  1249. return "", err
  1250. }
  1251. routing, _ := cfg["routing"].(map[string]any)
  1252. if routing == nil {
  1253. return "", nil
  1254. }
  1255. rules, _ := routing["rules"].([]any)
  1256. for _, r := range rules {
  1257. rule, ok := r.(map[string]any)
  1258. if !ok {
  1259. continue
  1260. }
  1261. if rule["balancerTag"] != target {
  1262. continue
  1263. }
  1264. inboundTags, ok := rule["inboundTag"].([]any)
  1265. if !ok || len(inboundTags) == 0 {
  1266. continue
  1267. }
  1268. if lbTag, ok := inboundTags[0].(string); ok && strings.HasPrefix(lbTag, "_bl_") {
  1269. return lbTag, nil
  1270. }
  1271. }
  1272. return "", nil
  1273. }
  1274. // TestRoute asks the running core which outbound its router picks for the
  1275. // described connection.
  1276. func (s *XrayService) TestRoute(req xray.RouteTestRequest) (*xray.RouteTestResult, error) {
  1277. process := currentXrayProcess()
  1278. if process == nil || !process.IsRunning() {
  1279. return nil, errors.New("xray is not running")
  1280. }
  1281. if err := s.xrayAPI.Init(process.GetAPIPort()); err != nil {
  1282. return nil, err
  1283. }
  1284. defer s.xrayAPI.Close()
  1285. return s.xrayAPI.TestRoute(req)
  1286. }
  1287. // RestartXray reconciles the running Xray process with the current desired
  1288. // config. When isForce is false it first tries to apply the changes through
  1289. // the Xray gRPC API without restarting the process (inbounds, outbounds and
  1290. // routing rules/balancers are hot-reloadable); only changes the core cannot
  1291. // take at runtime — or a force request — stop and restart the process.
  1292. func (s *XrayService) RestartXray(isForce bool) error {
  1293. lock.Lock()
  1294. defer lock.Unlock()
  1295. logger.Debug("restart Xray, force:", isForce)
  1296. if !isForce && isManuallyStopped.Load() {
  1297. return nil
  1298. }
  1299. isManuallyStopped.Store(false)
  1300. xrayConfig, err := s.GetXrayConfig()
  1301. if err != nil {
  1302. return err
  1303. }
  1304. process := currentXrayProcess()
  1305. if process != nil && process.IsRunning() {
  1306. configUnchanged := process.GetConfig().Equals(xrayConfig)
  1307. if !isForce && configUnchanged && !isNeedXrayRestart.Load() {
  1308. logger.Debug("It does not need to restart Xray")
  1309. return nil
  1310. }
  1311. // A config the core cannot bind never replaces one that works: its failed
  1312. // start exits the core, and the watchdog would then loop on it forever.
  1313. if conflicts := bindConflicts(xrayConfig, process.GetConfig()); len(conflicts) > 0 {
  1314. refused := fmt.Sprintf("config refused: %s", conflicts[0])
  1315. for _, conflict := range conflicts {
  1316. logger.Error("xray config refused:", conflict.String())
  1317. }
  1318. // The refusal is otherwise invisible: the operator's request
  1319. // succeeded, so the status page has to carry the stale state.
  1320. xrayState.holdBack(refused)
  1321. return fmt.Errorf("xray %s", refused)
  1322. }
  1323. if !isForce && !configUnchanged && s.tryHotApply(process, xrayConfig) {
  1324. logger.Info("Xray config changes applied through the core API, no restart needed")
  1325. return nil
  1326. }
  1327. _ = process.Stop()
  1328. } else if conflicts := bindConflicts(xrayConfig, nil); len(conflicts) > 0 {
  1329. // Nothing is running to protect and the core is the authority on what it
  1330. // can bind: start it and let its own error name the port it lost.
  1331. logger.Warning("xray config may not start:", conflicts[0].String())
  1332. }
  1333. process = xray.NewProcess(xrayConfig)
  1334. xrayState.replace(process)
  1335. s.xrayAPI.StatsLastValues = nil
  1336. err = process.Start()
  1337. if err != nil {
  1338. return err
  1339. }
  1340. return nil
  1341. }
  1342. // restartToDropClients reports whether a diff that strands clients must be
  1343. // applied by restarting instead of through the API.
  1344. func (s *XrayService) restartToDropClients(diff *xray.HotDiff) bool {
  1345. if diff == nil || !diff.DropsUsers() {
  1346. return false
  1347. }
  1348. restart, err := s.settingService.GetRestartXrayOnClientDisable()
  1349. if err != nil {
  1350. logger.Warning("get RestartXrayOnClientDisable failed:", err)
  1351. return false
  1352. }
  1353. return restart
  1354. }
  1355. // tryHotApply attempts to reconcile the running Xray instance with newCfg
  1356. // through the core gRPC API (HandlerService for inbounds/outbounds,
  1357. // RoutingService for rules/balancers). It returns true when the running
  1358. // instance now matches newCfg; on any failure it returns false and the
  1359. // caller falls back to a full process restart, which cleans up whatever was
  1360. // partially applied. Callers must hold the package-level lock.
  1361. func (s *XrayService) tryHotApply(process *xray.Process, newCfg *xray.Config) bool {
  1362. oldCfg := process.GetConfig()
  1363. diff, ok := xray.ComputeHotDiff(oldCfg, newCfg)
  1364. if !ok {
  1365. logger.Debug("hot apply: config change is not API-applicable, falling back to restart")
  1366. return false
  1367. }
  1368. if diff.Empty() {
  1369. process.SetConfig(newCfg)
  1370. persistHotConfig(process)
  1371. return true
  1372. }
  1373. // The core's RemoveUser drops the credential only, so a disabled or deleted
  1374. // client needs the restart this setting asks for.
  1375. if s.restartToDropClients(diff) {
  1376. logger.Info("hot apply: clients left the config, restarting to drop their live sessions")
  1377. return false
  1378. }
  1379. apiPort := process.GetAPIPort()
  1380. if apiPort <= 0 {
  1381. return false
  1382. }
  1383. // A dedicated client: s.xrayAPI may be in use by traffic polling on other
  1384. // service instances and is reset around restarts.
  1385. hotAPI := xray.XrayAPI{}
  1386. if err := hotAPI.Init(apiPort); err != nil {
  1387. logger.Debug("hot apply: failed to init xray api:", err)
  1388. return false
  1389. }
  1390. defer hotAPI.Close()
  1391. // Removals first so changed handlers and port swaps never collide with
  1392. // the additions that follow.
  1393. for _, u := range diff.RemovedUsers {
  1394. if err := hotAPI.RemoveUser(u.Tag, u.Email); err != nil && !xray.IsMissingHandlerErr(err) {
  1395. logger.Info("hot apply: remove user [", u.Email, "] from [", u.Tag, "] failed:", err)
  1396. return false
  1397. }
  1398. }
  1399. for _, tag := range diff.RemovedInboundTags {
  1400. if err := hotAPI.DelInbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  1401. logger.Info("hot apply: remove inbound [", tag, "] failed:", err)
  1402. return false
  1403. }
  1404. }
  1405. for _, tag := range diff.RemovedOutboundTags {
  1406. if err := hotAPI.DelOutbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  1407. logger.Info("hot apply: remove outbound [", tag, "] failed:", err)
  1408. return false
  1409. }
  1410. }
  1411. for _, ob := range diff.AddedOutbounds {
  1412. if err := addOutboundReconciling(&hotAPI, ob); err != nil {
  1413. logger.Info("hot apply: add outbound failed:", err)
  1414. return false
  1415. }
  1416. }
  1417. for _, ib := range diff.AddedInbounds {
  1418. if err := addInboundReconciling(&hotAPI, ib); err != nil {
  1419. logger.Info("hot apply: add inbound failed:", err)
  1420. return false
  1421. }
  1422. }
  1423. for _, u := range diff.AddedUsers {
  1424. if err := addUserReconciling(&hotAPI, u); err != nil {
  1425. logger.Info("hot apply: add user [", u.Email, "] to [", u.Tag, "] failed:", err)
  1426. return false
  1427. }
  1428. }
  1429. if diff.RoutingConfig != nil {
  1430. if err := hotAPI.ApplyRoutingConfig(diff.RoutingConfig); err != nil {
  1431. logger.Info("hot apply: apply routing config failed:", err)
  1432. return false
  1433. }
  1434. }
  1435. process.SetConfig(newCfg)
  1436. persistHotConfig(process)
  1437. return true
  1438. }
  1439. // persistHotConfig refreshes config.json after a hot apply; a write failure is
  1440. // logged only, since the running core already has the change.
  1441. func persistHotConfig(process *xray.Process) {
  1442. if err := process.PersistConfig(); err != nil {
  1443. logger.Warning("hot apply: failed to update config.json:", err)
  1444. }
  1445. }
  1446. // addUserReconciling adds a user, and on an email conflict (the user was
  1447. // already applied through the runtime API) replaces the existing user instead.
  1448. func addUserReconciling(api *xray.XrayAPI, u xray.UserOp) error {
  1449. err := api.AddUser(u.Protocol, u.Tag, u.User)
  1450. if err == nil || !xray.IsUserExistsErr(err) {
  1451. return err
  1452. }
  1453. if delErr := api.RemoveUser(u.Tag, u.Email); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  1454. return delErr
  1455. }
  1456. return api.AddUser(u.Protocol, u.Tag, u.User)
  1457. }
  1458. // addInboundReconciling adds an inbound, and on a tag conflict (the handler
  1459. // was already created through the runtime API while the stored snapshot was
  1460. // stale) replaces the existing handler instead.
  1461. func addInboundReconciling(api *xray.XrayAPI, inbound []byte) error {
  1462. err := api.AddInbound(inbound)
  1463. if err == nil || !xray.IsExistingTagErr(err) {
  1464. return err
  1465. }
  1466. var meta struct {
  1467. Tag string `json:"tag"`
  1468. }
  1469. if jsonErr := json.Unmarshal(inbound, &meta); jsonErr != nil || meta.Tag == "" {
  1470. return err
  1471. }
  1472. if delErr := api.DelInbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  1473. return delErr
  1474. }
  1475. return api.AddInbound(inbound)
  1476. }
  1477. // addOutboundReconciling mirrors addInboundReconciling for outbounds.
  1478. func addOutboundReconciling(api *xray.XrayAPI, outbound []byte) error {
  1479. err := api.AddOutbound(outbound)
  1480. if err == nil || !xray.IsExistingTagErr(err) {
  1481. return err
  1482. }
  1483. var meta struct {
  1484. Tag string `json:"tag"`
  1485. }
  1486. if jsonErr := json.Unmarshal(outbound, &meta); jsonErr != nil || meta.Tag == "" {
  1487. return err
  1488. }
  1489. if delErr := api.DelOutbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  1490. return delErr
  1491. }
  1492. return api.AddOutbound(outbound)
  1493. }
  1494. // StopXray stops the running Xray process.
  1495. func (s *XrayService) StopXray() error {
  1496. lock.Lock()
  1497. defer lock.Unlock()
  1498. isManuallyStopped.Store(true)
  1499. logger.Debug("Attempting to stop Xray...")
  1500. process := currentXrayProcess()
  1501. if process != nil && process.IsRunning() {
  1502. return process.Stop()
  1503. }
  1504. return errors.New("xray is not running")
  1505. }
  1506. // SetToNeedRestart marks that Xray needs to be restarted.
  1507. func (s *XrayService) SetToNeedRestart() {
  1508. isNeedXrayRestart.Store(true)
  1509. }
  1510. // GetXrayAPIPort returns the port the local xray process is listening on
  1511. // for its gRPC HandlerService, or 0 when xray isn't currently running.
  1512. // Exposed for the runtime package's LocalRuntime adapter without a
  1513. // service-package import cycle.
  1514. func (s *XrayService) GetXrayAPIPort() int {
  1515. process := currentXrayProcess()
  1516. if process == nil || !process.IsRunning() {
  1517. return 0
  1518. }
  1519. return process.GetAPIPort()
  1520. }
  1521. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  1522. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  1523. return isNeedXrayRestart.CompareAndSwap(true, false)
  1524. }
  1525. // ApplyPendingRestart consumes the need-restart flag and restarts Xray. If the
  1526. // restart fails (for example GetXrayConfig hits a transient DB error and leaves
  1527. // the old process running), it re-arms the flag so the next tick retries instead
  1528. // of silently dropping the pending config change.
  1529. func (s *XrayService) ApplyPendingRestart() {
  1530. if !s.IsNeedRestartAndSetFalse() {
  1531. return
  1532. }
  1533. if err := s.RestartXray(false); err != nil {
  1534. logger.Error("restart xray failed:", err)
  1535. s.SetToNeedRestart()
  1536. }
  1537. }
  1538. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  1539. func (s *XrayService) DidXrayCrash() bool {
  1540. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  1541. }
  1542. // liftXhttpSessionIDKeys renames the legacy XHTTP session keys
  1543. // (sessionPlacement/sessionKey) to the v26.6.22 #6258 names
  1544. // (sessionIDPlacement/sessionIDKey) inside a streamSettings map. xray-core kept
  1545. // no fallback for the old names, so a config stored before the rename would be
  1546. // silently ignored by the engine. Returns true if it changed anything.
  1547. func liftXhttpSessionIDKeys(stream map[string]any) bool {
  1548. xhttp, ok := stream["xhttpSettings"].(map[string]any)
  1549. if !ok {
  1550. return false
  1551. }
  1552. changed := false
  1553. for legacy, renamed := range map[string]string{
  1554. "sessionPlacement": "sessionIDPlacement",
  1555. "sessionKey": "sessionIDKey",
  1556. } {
  1557. v, has := xhttp[legacy]
  1558. if !has {
  1559. continue
  1560. }
  1561. if _, exists := xhttp[renamed]; !exists {
  1562. xhttp[renamed] = v
  1563. }
  1564. delete(xhttp, legacy)
  1565. changed = true
  1566. }
  1567. return changed
  1568. }
  1569. // liftOutboundsXhttpSessionIDKeys applies liftXhttpSessionIDKeys to every
  1570. // outbound's streamSettings in the raw outbounds array. The original bytes are
  1571. // returned untouched when nothing needs lifting, so an unchanged config never
  1572. // looks modified to the hot-reload diff.
  1573. func liftOutboundsXhttpSessionIDKeys(raw json_util.RawMessage) json_util.RawMessage {
  1574. if len(raw) == 0 {
  1575. return raw
  1576. }
  1577. var outbounds []map[string]any
  1578. if err := json.Unmarshal(raw, &outbounds); err != nil {
  1579. return raw
  1580. }
  1581. changed := false
  1582. for _, ob := range outbounds {
  1583. if stream, ok := ob["streamSettings"].(map[string]any); ok {
  1584. if liftXhttpSessionIDKeys(stream) {
  1585. changed = true
  1586. }
  1587. }
  1588. }
  1589. if !changed {
  1590. return raw
  1591. }
  1592. if rewritten, err := json.Marshal(outbounds); err == nil {
  1593. return rewritten
  1594. }
  1595. return raw
  1596. }