xray.go 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734
  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. // TUIC clients can connect to an IP while TLS carries a different or unresolvable SNI.
  718. // Keep sniffed domains available for routing without replacing the requested destination.
  719. tuicEgressSniffingSettings = `{"enabled":true,"destOverride":["http","tls","quic","fakedns"],"routeOnly":true}`
  720. )
  721. func injectTuicSocks(cfg *xray.Config, inbounds []*model.Inbound) {
  722. existingTags := make(map[string]struct{}, len(cfg.InboundConfigs))
  723. for i := range cfg.InboundConfigs {
  724. existingTags[cfg.InboundConfigs[i].Tag] = struct{}{}
  725. }
  726. for _, inbound := range inbounds {
  727. if inbound.Protocol != model.TUIC || !inbound.Enable || inbound.NodeID != nil {
  728. continue
  729. }
  730. if _, taken := existingTags[inbound.Tag]; taken {
  731. logger.Warning("tuic socks: inbound tag [", inbound.Tag, "] already present in generated config, skipping its relay inbound")
  732. continue
  733. }
  734. existingTags[inbound.Tag] = struct{}{}
  735. cfg.InboundConfigs = append(cfg.InboundConfigs, xray.InboundConfig{
  736. Listen: json_util.RawMessage(`"127.0.0.1"`),
  737. Port: tuic.SOCKSPortForInbound(inbound.Id),
  738. Protocol: "socks",
  739. Settings: json_util.RawMessage(tuicEgressSocksSettings),
  740. Sniffing: json_util.RawMessage(tuicEgressSniffingSettings),
  741. Tag: inbound.Tag,
  742. })
  743. }
  744. }
  745. // amneziawgV6EgressTag returns the stable, globally-unique freedom outbound
  746. // tag for one peer's IPv6 source-identity egress. Stable across config
  747. // regenerations (a pure function of two stable identifiers), so
  748. // internal/xray/hot_diff.go's tag-keyed outbound/routing diffing recognizes
  749. // "unchanged" rather than remove+recreate on every poll. The inbound.Id
  750. // prefix is defense in depth, not load-bearing on its own: email is already
  751. // enforced globally unique across the whole panel's client table
  752. // (model.ClientRecord.Email has a gorm uniqueIndex) — kept anyway since it
  753. // costs nothing and makes the tag self-describing, matching
  754. // NodeEgressInboundTag's own style.
  755. func amneziawgV6EgressTag(inboundID int, email string) string {
  756. return fmt.Sprintf("amneziawg-v6-%d-%s", inboundID, email)
  757. }
  758. // injectAmneziawgV6Egress gives every enabled, non-node-hosted AmneziaWG
  759. // peer with an IPv6 AllowedIPs entry its own single-purpose freedom
  760. // outbound, bound via sendThrough to that exact address, plus a routing
  761. // rule sending only that peer's IPv6-destined traffic through it — restoring the
  762. // per-client public IPv6 identity the hard cutover temporarily dropped
  763. // (Phase 3.5 of the migration plan). Scoped to outbound source identity
  764. // only: it depends on internal/amneziawgnet's own alias mechanism actually
  765. // giving the host that address at the OS level (see v6alias.go's
  766. // V6AliasesActive, the exact same gate this function uses below) — without
  767. // that, sendThrough fails to bind and every connection through it errors
  768. // outright (freedom.go's dial failure); there is no fallback outbound.
  769. //
  770. // The routing rule matches both inboundTag and user: SocksInboundSettings
  771. // (used by injectAmneziawgnetSocks above) already authenticates each
  772. // connection as the peer's own email via stock SOCKS5 auth, and a stock
  773. // Xray SOCKS5 inbound sets that connection's stats/routing identity from
  774. // the authenticated username — so "user" reliably isolates exactly one
  775. // peer's traffic, the same building block Finding 3 of the migration plan
  776. // already established for per-client stats.
  777. //
  778. // Modeled on injectNodeEgresses (the established N-per-slice inbound+rule
  779. // precedent, not injectAmneziawgnetSocks itself, which only ever emits a
  780. // single inbound and never touches outbounds/routing) and
  781. // mergeSubscriptionOutbounds's unmarshal-append-remarshal pattern for
  782. // cfg.OutboundConfigs. Synthetic rules are prepended ahead of whatever's
  783. // already in the routing rules array, the same pattern injectNodeEgresses/
  784. // injectMtprotoEgress already use for their own always-must-win infra
  785. // rules — this never touches the admin's own saved Routing-page rule
  786. // order.
  787. func injectAmneziawgV6Egress(cfg *xray.Config, inbounds []*model.Inbound) {
  788. // Protocol is checked alongside Tag, not just Tag alone: a tag collision
  789. // with some unrelated (non-socks) inbound must not be mistaken for this
  790. // instance's own relay having been created.
  791. liveInboundTags := make(map[string]struct{}, len(cfg.InboundConfigs))
  792. for i := range cfg.InboundConfigs {
  793. if cfg.InboundConfigs[i].Protocol == "socks" {
  794. liveInboundTags[cfg.InboundConfigs[i].Tag] = struct{}{}
  795. }
  796. }
  797. var existingOutbounds []any
  798. if len(cfg.OutboundConfigs) > 0 {
  799. if err := json.Unmarshal(cfg.OutboundConfigs, &existingOutbounds); err != nil {
  800. logger.Warning("amneziawg v6 egress: outbounds section is unparsable, skipping injection:", err)
  801. return
  802. }
  803. }
  804. usedOutboundTags := make(map[string]struct{}, len(existingOutbounds))
  805. for _, o := range existingOutbounds {
  806. if m, ok := o.(map[string]any); ok {
  807. if t, ok := m["tag"].(string); ok {
  808. usedOutboundTags[t] = struct{}{}
  809. }
  810. }
  811. }
  812. routing := map[string]any{}
  813. if len(cfg.RouterConfig) > 0 {
  814. if err := json.Unmarshal(cfg.RouterConfig, &routing); err != nil {
  815. logger.Warning("amneziawg v6 egress: routing section is unparsable, skipping injection:", err)
  816. return
  817. }
  818. }
  819. rules, _ := routing["rules"].([]any)
  820. newRules := make([]any, 0)
  821. newOutbounds := make([]any, 0)
  822. for _, inbound := range inbounds {
  823. if inbound.Protocol != model.AmneziaWG || !inbound.Enable || inbound.NodeID != nil {
  824. continue
  825. }
  826. if _, live := liveInboundTags[inbound.Tag]; !live {
  827. // The relay inbound itself wasn't created this pass (e.g. a tag
  828. // collision inside injectAmneziawgnetSocks) -- no SOCKS5 inbound
  829. // exists for hot_diff.go's inboundTag match to ever fire against.
  830. continue
  831. }
  832. inst, ok := amneziawg.InstanceFromInbound(inbound)
  833. if !ok || !amneziawgnet.V6AliasesActive(inst) {
  834. continue
  835. }
  836. for _, p := range inst.Peers {
  837. if p.Email == "" {
  838. continue
  839. }
  840. v6 := amneziawg.FirstIPv6(p.AllowedIPs)
  841. if v6 == "" {
  842. continue
  843. }
  844. tag := amneziawgV6EgressTag(inbound.Id, p.Email)
  845. if _, taken := usedOutboundTags[tag]; taken {
  846. logger.Warning("amneziawg v6 egress: outbound tag [", tag, "] already exists, skipping peer [", p.Email, "]")
  847. continue
  848. }
  849. usedOutboundTags[tag] = struct{}{}
  850. newOutbounds = append(newOutbounds, map[string]any{
  851. "tag": tag,
  852. "protocol": "freedom",
  853. "sendThrough": v6,
  854. "settings": map[string]any{},
  855. })
  856. newRules = append(newRules, map[string]any{
  857. "type": "field",
  858. "inboundTag": []any{inbound.Tag},
  859. "user": []any{p.Email},
  860. "ip": []any{"::/0"},
  861. "outboundTag": tag,
  862. })
  863. }
  864. }
  865. if len(newOutbounds) == 0 {
  866. return
  867. }
  868. merged := make([]any, 0, len(existingOutbounds))
  869. merged = append(merged, existingOutbounds...)
  870. merged = append(merged, newOutbounds...)
  871. combined, err := json.MarshalIndent(merged, "", " ")
  872. if err != nil {
  873. logger.Warning("amneziawg v6 egress: failed to rebuild outbounds section, skipping injection:", err)
  874. return
  875. }
  876. cfg.OutboundConfigs = json_util.RawMessage(combined)
  877. routing["rules"] = append(newRules, rules...)
  878. newRouting, err := json.Marshal(routing)
  879. if err != nil {
  880. logger.Warning("amneziawg v6 egress: failed to rebuild routing section, skipping injection:", err)
  881. return
  882. }
  883. cfg.RouterConfig = json_util.RawMessage(newRouting)
  884. }
  885. // mergeSubscriptionOutbounds appends the subscription outbounds to the
  886. // OutboundConfigs array of the xray config. It works on the already-unmarshaled
  887. // template so that manually configured outbounds are never overwritten.
  888. //
  889. // Safety: if we cannot parse the template's outbounds array, we leave
  890. // OutboundConfigs exactly as it came from the template (we do not inject
  891. // subscription outbounds). This prevents us from accidentally dropping the
  892. // user's manually configured outbounds when the template is in a weird state.
  893. func mergeSubscriptionOutbounds(cfg *xray.Config, prepend, appendList []any) {
  894. if len(prepend) == 0 && len(appendList) == 0 {
  895. return
  896. }
  897. var templateOutbounds []any
  898. if len(cfg.OutboundConfigs) > 0 {
  899. if err := json.Unmarshal(cfg.OutboundConfigs, &templateOutbounds); err != nil {
  900. // Corrupt template outbounds — do not touch the field at all.
  901. // The user will see problems on Xray start / next save.
  902. return
  903. }
  904. }
  905. var merged []any
  906. merged = append(merged, prepend...)
  907. merged = append(merged, templateOutbounds...)
  908. merged = append(merged, appendList...)
  909. combined, err := json.MarshalIndent(merged, "", " ")
  910. if err != nil {
  911. return
  912. }
  913. cfg.OutboundConfigs = json_util.RawMessage(combined)
  914. }
  915. // ensureAPIServices guarantees the gRPC services the panel depends on are
  916. // listed in the generated config's api block: HandlerService and StatsService
  917. // have always been required for inbound/user management and traffic polling,
  918. // and RoutingService enables hot routing reload on templates saved before it
  919. // was added to the default template. The stored template itself is not
  920. // modified — only the generated runtime config.
  921. func ensureAPIServices(api json_util.RawMessage) json_util.RawMessage {
  922. if len(api) == 0 {
  923. // No api block means the panel's API integration is deliberately
  924. // disabled; don't resurrect it behind the user's back.
  925. return api
  926. }
  927. var parsed map[string]any
  928. if err := json.Unmarshal(api, &parsed); err != nil {
  929. return api
  930. }
  931. services, _ := parsed["services"].([]any)
  932. have := make(map[string]bool, len(services))
  933. for _, svc := range services {
  934. if name, ok := svc.(string); ok {
  935. have[name] = true
  936. }
  937. }
  938. added := false
  939. for _, name := range []string{"HandlerService", "StatsService", "RoutingService"} {
  940. if !have[name] {
  941. services = append(services, name)
  942. added = true
  943. }
  944. }
  945. if !added {
  946. return api
  947. }
  948. parsed["services"] = services
  949. out, err := json.Marshal(parsed)
  950. if err != nil {
  951. return api
  952. }
  953. return out
  954. }
  955. // ensureStatsPolicy guarantees every policy level in the generated config has
  956. // statsUserOnline enabled, so the core tracks per-email online IPs for the
  957. // panel's online view and access-log-free IP limiting. Generated clients carry
  958. // no explicit level, so level "0" is created when absent. The flag is panel
  959. // infrastructure and is forced on even over an explicit false in the template,
  960. // same as the api services above. An entirely missing or unparsable policy
  961. // block is left alone; the stored template itself is never modified — only the
  962. // generated runtime config.
  963. func ensureStatsPolicy(policy json_util.RawMessage) json_util.RawMessage {
  964. if len(policy) == 0 {
  965. return policy
  966. }
  967. var parsed map[string]any
  968. if err := json.Unmarshal(policy, &parsed); err != nil {
  969. return policy
  970. }
  971. levels, _ := parsed["levels"].(map[string]any)
  972. if levels == nil {
  973. levels = make(map[string]any)
  974. }
  975. if _, ok := levels["0"]; !ok {
  976. levels["0"] = map[string]any{}
  977. }
  978. changed := false
  979. for _, raw := range levels {
  980. level, ok := raw.(map[string]any)
  981. if !ok {
  982. continue
  983. }
  984. if enabled, ok := level["statsUserOnline"].(bool); !ok || !enabled {
  985. level["statsUserOnline"] = true
  986. changed = true
  987. }
  988. }
  989. if !changed {
  990. return policy
  991. }
  992. parsed["levels"] = levels
  993. out, err := json.Marshal(parsed)
  994. if err != nil {
  995. return policy
  996. }
  997. return out
  998. }
  999. // caseVariantKeys returns every key of parsed that equals want ignoring case,
  1000. // lowest first so the fold is deterministic when several variants are present.
  1001. func caseVariantKeys(parsed map[string]any, want string) []string {
  1002. var keys []string
  1003. for key := range parsed {
  1004. if strings.EqualFold(key, want) {
  1005. keys = append(keys, key)
  1006. }
  1007. }
  1008. slices.Sort(keys)
  1009. return keys
  1010. }
  1011. func resolveXrayLogPaths(logCfg json_util.RawMessage) json_util.RawMessage {
  1012. if len(logCfg) == 0 {
  1013. return logCfg
  1014. }
  1015. var parsed map[string]any
  1016. if err := json.Unmarshal(logCfg, &parsed); err != nil {
  1017. return logCfg
  1018. }
  1019. changed := false
  1020. for _, key := range []string{"access", "error"} {
  1021. // xray-core decodes this object with encoding/json, whose case-insensitive
  1022. // field match makes "Access" reach AccessLog too — fold every variant.
  1023. variants := caseVariantKeys(parsed, key)
  1024. value, hasValue := parsed[key]
  1025. for _, variant := range variants {
  1026. if variant == key {
  1027. continue
  1028. }
  1029. if !hasValue {
  1030. value, hasValue = parsed[variant], true
  1031. }
  1032. delete(parsed, variant)
  1033. changed = true
  1034. }
  1035. v, ok := value.(string)
  1036. if !ok {
  1037. continue
  1038. }
  1039. trimmed := strings.TrimSpace(v)
  1040. if trimmed == "" || strings.EqualFold(trimmed, "none") {
  1041. if changed {
  1042. parsed[key] = v
  1043. }
  1044. continue
  1045. }
  1046. base := path.Base(filepath.ToSlash(trimmed))
  1047. if base == "" || base == "." || base == ".." || base == "/" {
  1048. continue
  1049. }
  1050. confined := filepath.Join(config.GetLogFolder(), base)
  1051. if confined == trimmed {
  1052. continue
  1053. }
  1054. parsed[key] = confined
  1055. changed = true
  1056. }
  1057. if !changed {
  1058. return logCfg
  1059. }
  1060. out, err := json.Marshal(parsed)
  1061. if err != nil {
  1062. return logCfg
  1063. }
  1064. return out
  1065. }
  1066. // stripDisabledRules removes routing rules marked `enabled: false` from the
  1067. // generated runtime config and strips panel-only keys (`enabled`, `comment`)
  1068. // from the rest, since xray-core has no such fields. The internal api rule is
  1069. // always kept (see isApiRule) so traffic stats can't be toggled off. The stored
  1070. // template is untouched — only the generated config is filtered.
  1071. func stripDisabledRules(routerCfg json_util.RawMessage) json_util.RawMessage {
  1072. if len(routerCfg) == 0 {
  1073. return routerCfg
  1074. }
  1075. var parsed map[string]any
  1076. if err := json.Unmarshal(routerCfg, &parsed); err != nil {
  1077. return routerCfg
  1078. }
  1079. rules, ok := parsed["rules"].([]any)
  1080. if !ok || len(rules) == 0 {
  1081. return routerCfg
  1082. }
  1083. var activeRules []any
  1084. changed := false
  1085. for _, rawRule := range rules {
  1086. rule, ok := rawRule.(map[string]any)
  1087. if !ok {
  1088. activeRules = append(activeRules, rawRule)
  1089. continue
  1090. }
  1091. if enabledRaw, exists := rule["enabled"]; exists {
  1092. // The internal api rule carries traffic stats and must never be
  1093. // dropped, even if it was somehow marked disabled.
  1094. enabled, ok := enabledRaw.(bool)
  1095. if ok && !enabled && !isApiRule(rule) {
  1096. changed = true
  1097. continue
  1098. }
  1099. delete(rule, "enabled")
  1100. changed = true
  1101. }
  1102. if _, exists := rule["comment"]; exists {
  1103. delete(rule, "comment")
  1104. changed = true
  1105. }
  1106. activeRules = append(activeRules, rule)
  1107. }
  1108. if !changed {
  1109. return routerCfg
  1110. }
  1111. parsed["rules"] = activeRules
  1112. out, err := json.Marshal(parsed)
  1113. if err != nil {
  1114. return routerCfg
  1115. }
  1116. return out
  1117. }
  1118. // GetXrayTraffic fetches the current traffic statistics from the running Xray process.
  1119. func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) {
  1120. process := currentXrayProcess()
  1121. if process == nil || !process.IsRunning() {
  1122. err := errors.New("xray is not running")
  1123. logger.Debug("Attempted to fetch Xray traffic, but Xray is not running:", err)
  1124. return nil, nil, err
  1125. }
  1126. apiPort := process.GetAPIPort()
  1127. if err := s.xrayAPI.Init(apiPort); err != nil {
  1128. logger.Debug("Failed to initialize Xray API:", err)
  1129. return nil, nil, err
  1130. }
  1131. defer s.xrayAPI.Close()
  1132. traffic, clientTraffic, err := s.xrayAPI.GetTraffic()
  1133. if err != nil {
  1134. logger.Debug("Failed to fetch Xray traffic:", err)
  1135. return nil, nil, err
  1136. }
  1137. return traffic, clientTraffic, nil
  1138. }
  1139. // GetOnlineUsers returns connection-based online users (email + source IPs)
  1140. // from the running core's online-stats API. ok=false means the API is not
  1141. // available — xray isn't running or the core predates the online-stats RPCs —
  1142. // and callers must use the legacy traffic-delta / access-log paths. The
  1143. // capability is probed lazily per process: an Unimplemented answer pins this
  1144. // core as unsupported until the next restart, while transient errors leave the
  1145. // capability undecided so a flaky poll can't lock in legacy mode.
  1146. func (s *XrayService) GetOnlineUsers() ([]xray.OnlineUser, bool, error) {
  1147. process := currentXrayProcess()
  1148. if process == nil || !process.IsRunning() {
  1149. return nil, false, nil
  1150. }
  1151. if process.OnlineAPISupport() == xray.OnlineAPIUnsupported {
  1152. return nil, false, nil
  1153. }
  1154. if err := s.xrayAPI.Init(process.GetAPIPort()); err != nil {
  1155. logger.Debug("Failed to initialize Xray API:", err)
  1156. return nil, false, err
  1157. }
  1158. defer s.xrayAPI.Close()
  1159. users, err := s.xrayAPI.GetOnlineUsers()
  1160. if err != nil {
  1161. if xray.IsUnimplementedErr(err) {
  1162. process.SetOnlineAPISupport(xray.OnlineAPIUnsupported)
  1163. logger.Info("xray core does not support the online-stats API; falling back to traffic-delta onlines and access-log IP limit")
  1164. return nil, false, nil
  1165. }
  1166. logger.Debug("Failed to fetch Xray online users:", err)
  1167. return nil, false, err
  1168. }
  1169. if process.OnlineAPISupport() == xray.OnlineAPIUnknown {
  1170. process.SetOnlineAPISupport(xray.OnlineAPISupported)
  1171. logger.Info("xray core supports the online-stats API; using connection-based onlines and access-log-free IP limit")
  1172. }
  1173. return users, true, nil
  1174. }
  1175. // BalancerStatus is the live view of one balancer for the panel UI. Running
  1176. // is false when the balancer isn't present in the running core (e.g. xray is
  1177. // stopped or the balancer hasn't been saved/applied yet).
  1178. type BalancerStatus struct {
  1179. Tag string `json:"tag"`
  1180. Running bool `json:"running"`
  1181. Override string `json:"override"`
  1182. Selected []string `json:"selected"`
  1183. }
  1184. // GetBalancersStatus queries the running core for the live state of the
  1185. // given balancer tags. Per-tag failures are reported as Running=false rather
  1186. // than failing the whole call, so the UI can render saved-but-not-applied
  1187. // balancers alongside live ones.
  1188. func (s *XrayService) GetBalancersStatus(tags []string) ([]BalancerStatus, error) {
  1189. statuses := make([]BalancerStatus, 0, len(tags))
  1190. process := currentXrayProcess()
  1191. if process == nil || !process.IsRunning() {
  1192. for _, tag := range tags {
  1193. statuses = append(statuses, BalancerStatus{Tag: tag})
  1194. }
  1195. return statuses, nil
  1196. }
  1197. if err := s.xrayAPI.Init(process.GetAPIPort()); err != nil {
  1198. return nil, err
  1199. }
  1200. defer s.xrayAPI.Close()
  1201. for _, tag := range tags {
  1202. info, err := s.xrayAPI.GetBalancerInfo(tag)
  1203. if err != nil {
  1204. logger.Debug("get balancer info [", tag, "] failed:", err)
  1205. statuses = append(statuses, BalancerStatus{Tag: tag})
  1206. continue
  1207. }
  1208. statuses = append(statuses, BalancerStatus{
  1209. Tag: tag,
  1210. Running: true,
  1211. Override: info.Override,
  1212. Selected: info.Selected,
  1213. })
  1214. }
  1215. return statuses, nil
  1216. }
  1217. // OverrideBalancer forces a balancer in the running core to use the given
  1218. // outbound tag; an empty target clears the override. When target names
  1219. // another balancer, the override resolves to the loopback outbound that
  1220. // routes traffic through the target balancer via the routing rules.
  1221. func (s *XrayService) OverrideBalancer(tag, target string) error {
  1222. process := currentXrayProcess()
  1223. if process == nil || !process.IsRunning() {
  1224. return errors.New("xray is not running")
  1225. }
  1226. if target != "" {
  1227. resolved, err := s.resolveOverrideTarget(target)
  1228. if err != nil {
  1229. return err
  1230. }
  1231. if resolved != "" {
  1232. target = resolved
  1233. }
  1234. }
  1235. if err := s.xrayAPI.Init(process.GetAPIPort()); err != nil {
  1236. return err
  1237. }
  1238. defer s.xrayAPI.Close()
  1239. return s.xrayAPI.SetBalancerTarget(tag, target)
  1240. }
  1241. // resolveOverrideTarget checks if target names a balancer and, if so,
  1242. // returns the loopback outbound tag that routes to it through the
  1243. // routing rules. Returns empty if target is already a concrete outbound.
  1244. func (s *XrayService) resolveOverrideTarget(target string) (string, error) {
  1245. template, err := s.settingService.GetXrayConfigTemplate()
  1246. if err != nil {
  1247. return "", err
  1248. }
  1249. var cfg map[string]any
  1250. if err := json.Unmarshal([]byte(template), &cfg); err != nil {
  1251. return "", err
  1252. }
  1253. routing, _ := cfg["routing"].(map[string]any)
  1254. if routing == nil {
  1255. return "", nil
  1256. }
  1257. rules, _ := routing["rules"].([]any)
  1258. for _, r := range rules {
  1259. rule, ok := r.(map[string]any)
  1260. if !ok {
  1261. continue
  1262. }
  1263. if rule["balancerTag"] != target {
  1264. continue
  1265. }
  1266. inboundTags, ok := rule["inboundTag"].([]any)
  1267. if !ok || len(inboundTags) == 0 {
  1268. continue
  1269. }
  1270. if lbTag, ok := inboundTags[0].(string); ok && strings.HasPrefix(lbTag, "_bl_") {
  1271. return lbTag, nil
  1272. }
  1273. }
  1274. return "", nil
  1275. }
  1276. // TestRoute asks the running core which outbound its router picks for the
  1277. // described connection.
  1278. func (s *XrayService) TestRoute(req xray.RouteTestRequest) (*xray.RouteTestResult, error) {
  1279. process := currentXrayProcess()
  1280. if process == nil || !process.IsRunning() {
  1281. return nil, errors.New("xray is not running")
  1282. }
  1283. if err := s.xrayAPI.Init(process.GetAPIPort()); err != nil {
  1284. return nil, err
  1285. }
  1286. defer s.xrayAPI.Close()
  1287. return s.xrayAPI.TestRoute(req)
  1288. }
  1289. // RestartXray reconciles the running Xray process with the current desired
  1290. // config. When isForce is false it first tries to apply the changes through
  1291. // the Xray gRPC API without restarting the process (inbounds, outbounds and
  1292. // routing rules/balancers are hot-reloadable); only changes the core cannot
  1293. // take at runtime — or a force request — stop and restart the process.
  1294. func (s *XrayService) RestartXray(isForce bool) error {
  1295. lock.Lock()
  1296. defer lock.Unlock()
  1297. logger.Debug("restart Xray, force:", isForce)
  1298. if !isForce && isManuallyStopped.Load() {
  1299. return nil
  1300. }
  1301. isManuallyStopped.Store(false)
  1302. xrayConfig, err := s.GetXrayConfig()
  1303. if err != nil {
  1304. return err
  1305. }
  1306. process := currentXrayProcess()
  1307. if process != nil && process.IsRunning() {
  1308. configUnchanged := process.GetConfig().Equals(xrayConfig)
  1309. if !isForce && configUnchanged && !isNeedXrayRestart.Load() {
  1310. logger.Debug("It does not need to restart Xray")
  1311. return nil
  1312. }
  1313. // A config the core cannot bind never replaces one that works: its failed
  1314. // start exits the core, and the watchdog would then loop on it forever.
  1315. if conflicts := bindConflicts(xrayConfig, process.GetConfig()); len(conflicts) > 0 {
  1316. refused := fmt.Sprintf("config refused: %s", conflicts[0])
  1317. for _, conflict := range conflicts {
  1318. logger.Error("xray config refused:", conflict.String())
  1319. }
  1320. // The refusal is otherwise invisible: the operator's request
  1321. // succeeded, so the status page has to carry the stale state.
  1322. xrayState.holdBack(refused)
  1323. return fmt.Errorf("xray %s", refused)
  1324. }
  1325. if !isForce && !configUnchanged && s.tryHotApply(process, xrayConfig) {
  1326. logger.Info("Xray config changes applied through the core API, no restart needed")
  1327. return nil
  1328. }
  1329. _ = process.Stop()
  1330. } else if conflicts := bindConflicts(xrayConfig, nil); len(conflicts) > 0 {
  1331. // Nothing is running to protect and the core is the authority on what it
  1332. // can bind: start it and let its own error name the port it lost.
  1333. logger.Warning("xray config may not start:", conflicts[0].String())
  1334. }
  1335. process = xray.NewProcess(xrayConfig)
  1336. xrayState.replace(process)
  1337. s.xrayAPI.StatsLastValues = nil
  1338. err = process.Start()
  1339. if err != nil {
  1340. return err
  1341. }
  1342. return nil
  1343. }
  1344. // restartToDropClients reports whether a diff that strands clients must be
  1345. // applied by restarting instead of through the API.
  1346. func (s *XrayService) restartToDropClients(diff *xray.HotDiff) bool {
  1347. if diff == nil || !diff.DropsUsers() {
  1348. return false
  1349. }
  1350. restart, err := s.settingService.GetRestartXrayOnClientDisable()
  1351. if err != nil {
  1352. logger.Warning("get RestartXrayOnClientDisable failed:", err)
  1353. return false
  1354. }
  1355. return restart
  1356. }
  1357. // tryHotApply attempts to reconcile the running Xray instance with newCfg
  1358. // through the core gRPC API (HandlerService for inbounds/outbounds,
  1359. // RoutingService for rules/balancers). It returns true when the running
  1360. // instance now matches newCfg; on any failure it returns false and the
  1361. // caller falls back to a full process restart, which cleans up whatever was
  1362. // partially applied. Callers must hold the package-level lock.
  1363. func (s *XrayService) tryHotApply(process *xray.Process, newCfg *xray.Config) bool {
  1364. oldCfg := process.GetConfig()
  1365. diff, ok := xray.ComputeHotDiff(oldCfg, newCfg)
  1366. if !ok {
  1367. logger.Debug("hot apply: config change is not API-applicable, falling back to restart")
  1368. return false
  1369. }
  1370. if diff.Empty() {
  1371. process.SetConfig(newCfg)
  1372. persistHotConfig(process)
  1373. return true
  1374. }
  1375. // The core's RemoveUser drops the credential only, so a disabled or deleted
  1376. // client needs the restart this setting asks for.
  1377. if s.restartToDropClients(diff) {
  1378. logger.Info("hot apply: clients left the config, restarting to drop their live sessions")
  1379. return false
  1380. }
  1381. apiPort := process.GetAPIPort()
  1382. if apiPort <= 0 {
  1383. return false
  1384. }
  1385. // A dedicated client: s.xrayAPI may be in use by traffic polling on other
  1386. // service instances and is reset around restarts.
  1387. hotAPI := xray.XrayAPI{}
  1388. if err := hotAPI.Init(apiPort); err != nil {
  1389. logger.Debug("hot apply: failed to init xray api:", err)
  1390. return false
  1391. }
  1392. defer hotAPI.Close()
  1393. // Removals first so changed handlers and port swaps never collide with
  1394. // the additions that follow.
  1395. for _, u := range diff.RemovedUsers {
  1396. if err := hotAPI.RemoveUser(u.Tag, u.Email); err != nil && !xray.IsMissingHandlerErr(err) {
  1397. logger.Info("hot apply: remove user [", u.Email, "] from [", u.Tag, "] failed:", err)
  1398. return false
  1399. }
  1400. }
  1401. for _, tag := range diff.RemovedInboundTags {
  1402. if err := hotAPI.DelInbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  1403. logger.Info("hot apply: remove inbound [", tag, "] failed:", err)
  1404. return false
  1405. }
  1406. }
  1407. for _, tag := range diff.RemovedOutboundTags {
  1408. if err := hotAPI.DelOutbound(tag); err != nil && !xray.IsMissingHandlerErr(err) {
  1409. logger.Info("hot apply: remove outbound [", tag, "] failed:", err)
  1410. return false
  1411. }
  1412. }
  1413. for _, ob := range diff.AddedOutbounds {
  1414. if err := addOutboundReconciling(&hotAPI, ob); err != nil {
  1415. logger.Info("hot apply: add outbound failed:", err)
  1416. return false
  1417. }
  1418. }
  1419. for _, ib := range diff.AddedInbounds {
  1420. if err := addInboundReconciling(&hotAPI, ib); err != nil {
  1421. logger.Info("hot apply: add inbound failed:", err)
  1422. return false
  1423. }
  1424. }
  1425. for _, u := range diff.AddedUsers {
  1426. if err := addUserReconciling(&hotAPI, u); err != nil {
  1427. logger.Info("hot apply: add user [", u.Email, "] to [", u.Tag, "] failed:", err)
  1428. return false
  1429. }
  1430. }
  1431. if diff.RoutingConfig != nil {
  1432. if err := hotAPI.ApplyRoutingConfig(diff.RoutingConfig); err != nil {
  1433. logger.Info("hot apply: apply routing config failed:", err)
  1434. return false
  1435. }
  1436. }
  1437. process.SetConfig(newCfg)
  1438. persistHotConfig(process)
  1439. return true
  1440. }
  1441. // persistHotConfig refreshes config.json after a hot apply; a write failure is
  1442. // logged only, since the running core already has the change.
  1443. func persistHotConfig(process *xray.Process) {
  1444. if err := process.PersistConfig(); err != nil {
  1445. logger.Warning("hot apply: failed to update config.json:", err)
  1446. }
  1447. }
  1448. // addUserReconciling adds a user, and on an email conflict (the user was
  1449. // already applied through the runtime API) replaces the existing user instead.
  1450. func addUserReconciling(api *xray.XrayAPI, u xray.UserOp) error {
  1451. err := api.AddUser(u.Protocol, u.Tag, u.User)
  1452. if err == nil || !xray.IsUserExistsErr(err) {
  1453. return err
  1454. }
  1455. if delErr := api.RemoveUser(u.Tag, u.Email); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  1456. return delErr
  1457. }
  1458. return api.AddUser(u.Protocol, u.Tag, u.User)
  1459. }
  1460. // addInboundReconciling adds an inbound, and on a tag conflict (the handler
  1461. // was already created through the runtime API while the stored snapshot was
  1462. // stale) replaces the existing handler instead.
  1463. func addInboundReconciling(api *xray.XrayAPI, inbound []byte) error {
  1464. err := api.AddInbound(inbound)
  1465. if err == nil || !xray.IsExistingTagErr(err) {
  1466. return err
  1467. }
  1468. var meta struct {
  1469. Tag string `json:"tag"`
  1470. }
  1471. if jsonErr := json.Unmarshal(inbound, &meta); jsonErr != nil || meta.Tag == "" {
  1472. return err
  1473. }
  1474. if delErr := api.DelInbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  1475. return delErr
  1476. }
  1477. return api.AddInbound(inbound)
  1478. }
  1479. // addOutboundReconciling mirrors addInboundReconciling for outbounds.
  1480. func addOutboundReconciling(api *xray.XrayAPI, outbound []byte) error {
  1481. err := api.AddOutbound(outbound)
  1482. if err == nil || !xray.IsExistingTagErr(err) {
  1483. return err
  1484. }
  1485. var meta struct {
  1486. Tag string `json:"tag"`
  1487. }
  1488. if jsonErr := json.Unmarshal(outbound, &meta); jsonErr != nil || meta.Tag == "" {
  1489. return err
  1490. }
  1491. if delErr := api.DelOutbound(meta.Tag); delErr != nil && !xray.IsMissingHandlerErr(delErr) {
  1492. return delErr
  1493. }
  1494. return api.AddOutbound(outbound)
  1495. }
  1496. // StopXray stops the running Xray process.
  1497. func (s *XrayService) StopXray() error {
  1498. lock.Lock()
  1499. defer lock.Unlock()
  1500. isManuallyStopped.Store(true)
  1501. logger.Debug("Attempting to stop Xray...")
  1502. process := currentXrayProcess()
  1503. if process != nil && process.IsRunning() {
  1504. return process.Stop()
  1505. }
  1506. return errors.New("xray is not running")
  1507. }
  1508. // SetToNeedRestart marks that Xray needs to be restarted.
  1509. func (s *XrayService) SetToNeedRestart() {
  1510. isNeedXrayRestart.Store(true)
  1511. }
  1512. // GetXrayAPIPort returns the port the local xray process is listening on
  1513. // for its gRPC HandlerService, or 0 when xray isn't currently running.
  1514. // Exposed for the runtime package's LocalRuntime adapter without a
  1515. // service-package import cycle.
  1516. func (s *XrayService) GetXrayAPIPort() int {
  1517. process := currentXrayProcess()
  1518. if process == nil || !process.IsRunning() {
  1519. return 0
  1520. }
  1521. return process.GetAPIPort()
  1522. }
  1523. // IsNeedRestartAndSetFalse checks if restart is needed and resets the flag to false.
  1524. func (s *XrayService) IsNeedRestartAndSetFalse() bool {
  1525. return isNeedXrayRestart.CompareAndSwap(true, false)
  1526. }
  1527. // ApplyPendingRestart consumes the need-restart flag and restarts Xray. If the
  1528. // restart fails (for example GetXrayConfig hits a transient DB error and leaves
  1529. // the old process running), it re-arms the flag so the next tick retries instead
  1530. // of silently dropping the pending config change.
  1531. func (s *XrayService) ApplyPendingRestart() {
  1532. if !s.IsNeedRestartAndSetFalse() {
  1533. return
  1534. }
  1535. if err := s.RestartXray(false); err != nil {
  1536. logger.Error("restart xray failed:", err)
  1537. s.SetToNeedRestart()
  1538. }
  1539. }
  1540. // DidXrayCrash checks if Xray crashed by verifying it's not running and wasn't manually stopped.
  1541. func (s *XrayService) DidXrayCrash() bool {
  1542. return !s.IsXrayRunning() && !isManuallyStopped.Load()
  1543. }
  1544. // liftXhttpSessionIDKeys renames the legacy XHTTP session keys
  1545. // (sessionPlacement/sessionKey) to the v26.6.22 #6258 names
  1546. // (sessionIDPlacement/sessionIDKey) inside a streamSettings map. xray-core kept
  1547. // no fallback for the old names, so a config stored before the rename would be
  1548. // silently ignored by the engine. Returns true if it changed anything.
  1549. func liftXhttpSessionIDKeys(stream map[string]any) bool {
  1550. xhttp, ok := stream["xhttpSettings"].(map[string]any)
  1551. if !ok {
  1552. return false
  1553. }
  1554. changed := false
  1555. for legacy, renamed := range map[string]string{
  1556. "sessionPlacement": "sessionIDPlacement",
  1557. "sessionKey": "sessionIDKey",
  1558. } {
  1559. v, has := xhttp[legacy]
  1560. if !has {
  1561. continue
  1562. }
  1563. if _, exists := xhttp[renamed]; !exists {
  1564. xhttp[renamed] = v
  1565. }
  1566. delete(xhttp, legacy)
  1567. changed = true
  1568. }
  1569. return changed
  1570. }
  1571. // liftOutboundsXhttpSessionIDKeys applies liftXhttpSessionIDKeys to every
  1572. // outbound's streamSettings in the raw outbounds array. The original bytes are
  1573. // returned untouched when nothing needs lifting, so an unchanged config never
  1574. // looks modified to the hot-reload diff.
  1575. func liftOutboundsXhttpSessionIDKeys(raw json_util.RawMessage) json_util.RawMessage {
  1576. if len(raw) == 0 {
  1577. return raw
  1578. }
  1579. var outbounds []map[string]any
  1580. if err := json.Unmarshal(raw, &outbounds); err != nil {
  1581. return raw
  1582. }
  1583. changed := false
  1584. for _, ob := range outbounds {
  1585. if stream, ok := ob["streamSettings"].(map[string]any); ok {
  1586. if liftXhttpSessionIDKeys(stream) {
  1587. changed = true
  1588. }
  1589. }
  1590. }
  1591. if !changed {
  1592. return raw
  1593. }
  1594. if rewritten, err := json.Marshal(outbounds); err == nil {
  1595. return rewritten
  1596. }
  1597. return raw
  1598. }