1
0

xray.go 57 KB

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