1
0

xray.go 52 KB

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