xray.go 57 KB

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