xray_setting.go 11 KB

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