xray.go 53 KB

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