xray.go 55 KB

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