1
0

xray.go 55 KB

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