1
0

xray_setting.go 9.4 KB

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