1
0

xray_setting.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. package service
  2. import (
  3. _ "embed"
  4. "encoding/base64"
  5. "encoding/json"
  6. "slices"
  7. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  8. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  9. )
  10. // XraySettingService provides business logic for Xray configuration management.
  11. // It handles validation and storage of Xray template configurations.
  12. type XraySettingService struct {
  13. SettingService
  14. }
  15. func (s *XraySettingService) SaveXraySetting(newXraySettings string) error {
  16. // The frontend round-trips the whole getXraySetting response back
  17. // through the textarea, so if it has ever received a wrapped
  18. // payload (see UnwrapXrayTemplateConfig) it sends that same wrapper
  19. // back here. Strip it before validation/storage, otherwise we save
  20. // garbage the next read can't recover from without this same call.
  21. newXraySettings = UnwrapXrayTemplateConfig(newXraySettings)
  22. if err := s.CheckXrayConfig(newXraySettings); err != nil {
  23. return err
  24. }
  25. if hoisted, err := EnsureStatsRouting(newXraySettings); err == nil {
  26. newXraySettings = hoisted
  27. }
  28. if synced, err := EnsureDnsServerRouting(newXraySettings); err == nil {
  29. newXraySettings = synced
  30. }
  31. return s.saveSetting("xrayTemplateConfig", newXraySettings)
  32. }
  33. func (s *XraySettingService) CheckXrayConfig(XrayTemplateConfig string) error {
  34. xrayConfig := &xray.Config{}
  35. err := json.Unmarshal([]byte(XrayTemplateConfig), xrayConfig)
  36. if err != nil {
  37. return common.NewError("xray template config invalid:", err)
  38. }
  39. return nil
  40. }
  41. func (s *XraySettingService) UpdateWarpXraySetting(warpData map[string]string, warpConfig map[string]any) error {
  42. template, err := s.GetXrayConfigTemplate()
  43. if err != nil {
  44. return err
  45. }
  46. var cfg map[string]any
  47. if err := json.Unmarshal([]byte(template), &cfg); err != nil {
  48. return err
  49. }
  50. outbounds, ok := cfg["outbounds"].([]any)
  51. if !ok {
  52. return nil
  53. }
  54. updated := false
  55. for _, outIface := range outbounds {
  56. out, ok := outIface.(map[string]any)
  57. if !ok {
  58. continue
  59. }
  60. if tag, ok := out["tag"].(string); ok && tag == "warp" {
  61. settings, ok := out["settings"].(map[string]any)
  62. if !ok {
  63. continue
  64. }
  65. settings["secretKey"] = warpData["private_key"]
  66. if conf, ok := warpConfig["config"].(map[string]any); ok {
  67. if iface, ok := conf["interface"].(map[string]any); ok {
  68. if addrs, ok := iface["addresses"].(map[string]any); ok {
  69. var addrList []string
  70. if v4, ok := addrs["v4"].(string); ok && v4 != "" {
  71. addrList = append(addrList, v4+"/32")
  72. }
  73. if v6, ok := addrs["v6"].(string); ok && v6 != "" {
  74. addrList = append(addrList, v6+"/128")
  75. }
  76. settings["address"] = addrList
  77. }
  78. }
  79. var clientId string
  80. if id, ok := conf["client_id"].(string); ok {
  81. clientId = id
  82. } else if id, ok := warpData["client_id"]; ok {
  83. clientId = id
  84. }
  85. if clientId != "" {
  86. decoded, _ := base64.StdEncoding.DecodeString(clientId)
  87. var res []int
  88. for _, b := range decoded {
  89. res = append(res, int(b))
  90. }
  91. settings["reserved"] = res
  92. }
  93. if peers, ok := conf["peers"].([]any); ok && len(peers) > 0 {
  94. if peer, ok := peers[0].(map[string]any); ok {
  95. if pSettings, ok := settings["peers"].([]any); ok && len(pSettings) > 0 {
  96. if pSet, ok := pSettings[0].(map[string]any); ok {
  97. pSet["publicKey"] = peer["public_key"]
  98. if endpoint, ok := peer["endpoint"].(map[string]any); ok {
  99. pSet["endpoint"] = endpoint["host"]
  100. }
  101. }
  102. }
  103. }
  104. }
  105. }
  106. updated = true
  107. break
  108. }
  109. }
  110. if updated {
  111. outJSON, err := json.MarshalIndent(cfg, "", " ")
  112. if err != nil {
  113. return err
  114. }
  115. return s.SaveXraySetting(string(outJSON))
  116. }
  117. return nil
  118. }
  119. // UnwrapXrayTemplateConfig returns the raw xray config JSON from `raw`,
  120. // peeling off any number of `{ "inboundTags": ..., "outboundTestUrl": ...,
  121. // "xraySetting": <real config> }` response-shaped wrappers that may have
  122. // ended up in the database.
  123. //
  124. // How it got there: getXraySetting used to embed the raw DB value as
  125. // `xraySetting` in its response without checking whether the stored
  126. // value was already that exact response shape. If the frontend then
  127. // saved it verbatim (the textarea is a round-trip of the JSON it was
  128. // handed), the wrapper got persisted — and each subsequent save nested
  129. // another layer, producing the blank Xray Settings page reported in
  130. // issue #4059.
  131. //
  132. // If `raw` does not look like a wrapper, it is returned unchanged.
  133. func UnwrapXrayTemplateConfig(raw string) string {
  134. const maxDepth = 8 // defensive cap against pathological multi-nest values
  135. for range maxDepth {
  136. var top map[string]json.RawMessage
  137. if err := json.Unmarshal([]byte(raw), &top); err != nil {
  138. return raw
  139. }
  140. inner, ok := top["xraySetting"]
  141. if !ok {
  142. return raw
  143. }
  144. // Real xray configs never contain a top-level "xraySetting" key,
  145. // but they do contain things like "inbounds"/"outbounds"/"api".
  146. // If any of those are present, we're already at the real config
  147. // and the "xraySetting" field is either user data or coincidence
  148. // — don't touch it.
  149. for _, k := range []string{"inbounds", "outbounds", "routing", "api", "dns", "log", "policy", "stats"} {
  150. if _, hit := top[k]; hit {
  151. return raw
  152. }
  153. }
  154. // Peel off one layer.
  155. unwrapped := string(inner)
  156. // `xraySetting` may be stored either as a JSON object or as a
  157. // JSON-encoded string of an object. Handle both.
  158. var asStr string
  159. if err := json.Unmarshal(inner, &asStr); err == nil {
  160. unwrapped = asStr
  161. }
  162. raw = unwrapped
  163. }
  164. return raw
  165. }
  166. // EnsureStatsRouting hoists the `api -> api` routing rule to the front
  167. // of routing.rules so the stats query path is never starved by a
  168. // catch-all rule the admin may have added or reordered above it.
  169. //
  170. // Why this matters (#4113, #2818): an admin who adds a cascade outbound
  171. // (e.g. vless to another server) and a routing rule sending all inbound
  172. // traffic to it ends up sending the internal stats inbound's traffic to
  173. // that cascade too, since rules are evaluated top-to-bottom and the
  174. // catch-all matches first. The panel's gRPC stats query then can't reach
  175. // the running xray instance, GetTraffic returns nothing, and every
  176. // client appears offline with zero traffic even though the actual proxy
  177. // path works fine.
  178. //
  179. // The api inbound is special-cased internal infrastructure for the
  180. // panel, not something the admin should ever route to a real outbound.
  181. // Keeping its rule pinned at index 0 is the only correct configuration.
  182. //
  183. // If the api rule is already at index 0 the input is returned unchanged.
  184. // If it exists somewhere else it is moved. If it is missing entirely a
  185. // default rule (`type=field, inboundTag=[api], outboundTag=api`) is
  186. // inserted at the front. Other routing entries keep their relative order.
  187. func EnsureStatsRouting(raw string) (string, error) {
  188. var cfg map[string]json.RawMessage
  189. if err := json.Unmarshal([]byte(raw), &cfg); err != nil {
  190. return raw, err
  191. }
  192. var routing map[string]json.RawMessage
  193. if r, ok := cfg["routing"]; ok && len(r) > 0 {
  194. if err := json.Unmarshal(r, &routing); err != nil {
  195. return raw, err
  196. }
  197. }
  198. if routing == nil {
  199. routing = make(map[string]json.RawMessage)
  200. }
  201. var rules []map[string]any
  202. if r, ok := routing["rules"]; ok && len(r) > 0 {
  203. if err := json.Unmarshal(r, &rules); err != nil {
  204. return raw, err
  205. }
  206. }
  207. apiIdx := findApiRule(rules)
  208. if apiIdx == 0 {
  209. return raw, nil // already correct, don't churn the JSON
  210. }
  211. var apiRule map[string]any
  212. if apiIdx > 0 {
  213. apiRule = rules[apiIdx]
  214. rules = append(rules[:apiIdx], rules[apiIdx+1:]...)
  215. } else {
  216. apiRule = map[string]any{
  217. "type": "field",
  218. "inboundTag": []string{"api"},
  219. "outboundTag": "api",
  220. }
  221. }
  222. delete(apiRule, "enabled")
  223. rules = append([]map[string]any{apiRule}, rules...)
  224. rulesJSON, err := json.Marshal(rules)
  225. if err != nil {
  226. return raw, err
  227. }
  228. routing["rules"] = rulesJSON
  229. routingJSON, err := json.Marshal(routing)
  230. if err != nil {
  231. return raw, err
  232. }
  233. cfg["routing"] = routingJSON
  234. out, err := json.Marshal(cfg)
  235. if err != nil {
  236. return raw, err
  237. }
  238. return string(out), nil
  239. }
  240. // isApiRule reports whether a routing rule targets the internal api inbound
  241. // (inboundTag contains "api" and outboundTag is "api").
  242. func isApiRule(rule map[string]any) bool {
  243. if outTag, _ := rule["outboundTag"].(string); outTag != "api" {
  244. return false
  245. }
  246. raw, ok := rule["inboundTag"]
  247. if !ok {
  248. return false
  249. }
  250. // inboundTag is usually []string but can come as []any from a
  251. // roundtrip through map[string]any. Accept both shapes.
  252. switch tags := raw.(type) {
  253. case []any:
  254. for _, t := range tags {
  255. if s, ok := t.(string); ok && s == "api" {
  256. return true
  257. }
  258. }
  259. case []string:
  260. if slices.Contains(tags, "api") {
  261. return true
  262. }
  263. case string:
  264. if tags == "api" {
  265. return true
  266. }
  267. }
  268. return false
  269. }
  270. // findApiRule returns the index of the routing rule that targets the
  271. // internal api inbound, or -1 if no such rule exists.
  272. func findApiRule(rules []map[string]any) int {
  273. for i, rule := range rules {
  274. if isApiRule(rule) {
  275. return i
  276. }
  277. }
  278. return -1
  279. }