1
0

json_service.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. package sub
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "fmt"
  6. "maps"
  7. "net/url"
  8. "slices"
  9. "sort"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  15. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  16. "github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
  17. "github.com/mhsanaei/3x-ui/v3/internal/util/random"
  18. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  19. )
  20. //go:embed default.json
  21. var defaultJson string
  22. // SubJsonService handles JSON subscription configuration generation and management.
  23. type SubJsonService struct {
  24. configJson map[string]any
  25. defaultOutbounds []json_util.RawMessage
  26. finalMask string
  27. mux string
  28. observatory subBalancerObservatoryConfig
  29. // bakedRouting is re-resolved per request: a remote URL may be cold at
  30. // construction time and warm up later via the cron job.
  31. routingRules string
  32. bakedRoutingMu sync.Mutex
  33. bakedRouting *bakedRoutingState
  34. // dnsBlock is the panel DNS override, fixed for the service's lifetime.
  35. dnsBlock map[string]any
  36. SubService *SubService
  37. }
  38. type bakedRoutingState struct {
  39. spec jsonRoutingSpec
  40. configJson map[string]any
  41. }
  42. // NewSubJsonService creates a new JSON subscription service with the given configuration.
  43. func NewSubJsonService(mux string, rules string, finalMask string, routingRules string, subService *SubService) *SubJsonService {
  44. var configJson map[string]any
  45. var defaultOutbounds []json_util.RawMessage
  46. _ = json.Unmarshal([]byte(defaultJson), &configJson)
  47. if outboundSlices, ok := configJson["outbounds"].([]any); ok {
  48. for _, defaultOutbound := range outboundSlices {
  49. jsonBytes, _ := json.Marshal(defaultOutbound)
  50. defaultOutbounds = append(defaultOutbounds, jsonBytes)
  51. }
  52. }
  53. // A baked routing profile replaces the template's dns and routing subtrees
  54. // outright; the legacy simple-rules setting only applies without a profile.
  55. if routingRules == "" && rules != "" {
  56. var newRules []any
  57. routing, _ := configJson["routing"].(map[string]any)
  58. defaultRules, _ := routing["rules"].([]any)
  59. _ = json.Unmarshal([]byte(rules), &newRules)
  60. defaultRules = append(newRules, defaultRules...)
  61. routing["rules"] = defaultRules
  62. configJson["routing"] = routing
  63. }
  64. return &SubJsonService{
  65. configJson: configJson,
  66. defaultOutbounds: defaultOutbounds,
  67. finalMask: finalMask,
  68. mux: mux,
  69. routingRules: routingRules,
  70. observatory: defaultSubBalancerObservatoryConfig(),
  71. SubService: subService,
  72. }
  73. }
  74. // Re-resolved per call so an upstream edit reaches the documents without a
  75. // restart; a failed resolve keeps the last good template.
  76. func (s *SubJsonService) bakedTemplate() map[string]any {
  77. if s.routingRules == "" && s.dnsBlock == nil {
  78. return s.configJson
  79. }
  80. spec := resolveJsonRoutingSpec(s.routingRules)
  81. s.bakedRoutingMu.Lock()
  82. defer s.bakedRoutingMu.Unlock()
  83. if s.bakedRouting != nil {
  84. if spec.empty() || spec.equal(s.bakedRouting.spec) {
  85. return s.bakedRouting.configJson
  86. }
  87. } else if spec.empty() && s.dnsBlock == nil {
  88. return s.configJson
  89. }
  90. template := make(map[string]any, len(s.configJson)+2)
  91. maps.Copy(template, s.configJson)
  92. if !spec.empty() {
  93. applyJsonRouting(template, spec)
  94. }
  95. // The panel-level DNS block is an explicit choice, so it also replaces the
  96. // dns subtree a routing profile would otherwise bake in.
  97. if s.dnsBlock != nil {
  98. template["dns"] = s.dnsBlock
  99. }
  100. s.bakedRouting = &bakedRoutingState{spec: spec, configJson: template}
  101. return template
  102. }
  103. // GetJson generates a JSON subscription configuration for the given subscription ID and host.
  104. func (s *SubJsonService) GetJson(subId string, host string, alwaysReturnArray bool) (string, string, error) {
  105. subReq := s.SubService.ForRequest(host)
  106. subReq.subscriptionBody = true
  107. inbounds, err := subReq.getInboundsBySubId(subId)
  108. if err != nil {
  109. return "", "", err
  110. }
  111. externalLinks, err := subReq.getClientExternalLinksBySubId(subId)
  112. if err != nil {
  113. return "", "", err
  114. }
  115. if len(inbounds) == 0 && len(externalLinks) == 0 {
  116. return "", "", nil
  117. }
  118. var header string
  119. var hasInactiveExternal bool
  120. var hasEnabledClient bool
  121. seenEmails := make(map[string]struct{})
  122. entries := make([]subConfigEntry, 0, len(inbounds))
  123. // Prepare Inbounds
  124. for _, inbound := range inbounds {
  125. clients := subReq.matchingClients(inbound, subId)
  126. if len(clients) == 0 {
  127. continue
  128. }
  129. if inbound.ExcludeFromSub {
  130. if countHiddenClients(clients, seenEmails) {
  131. hasEnabledClient = true
  132. }
  133. continue
  134. }
  135. subReq.projectThroughFallbackMaster(inbound)
  136. if hostEps := subReq.hostEndpoints(inbound, "json"); len(hostEps) > 0 {
  137. injectExternalProxy(inbound, hostEps)
  138. }
  139. var inboundConfigs []json_util.RawMessage
  140. for _, client := range clients {
  141. if client.Enable {
  142. hasEnabledClient = true
  143. }
  144. seenEmails[client.Email] = struct{}{}
  145. inboundConfigs = append(inboundConfigs, s.getConfig(subReq, inbound, client, host)...)
  146. }
  147. if len(inboundConfigs) > 0 {
  148. entries = append(entries, subConfigEntry{
  149. sortIndex: inbound.SubSortIndex,
  150. id: inbound.Id,
  151. configs: inboundConfigs,
  152. })
  153. }
  154. }
  155. entries = s.appendBalancerEntries(entries)
  156. // Inbounds arrive sorted by (sub_sort_index, id); balancers interleave by
  157. // the same key and, on an equal number, follow the inbound group.
  158. sort.SliceStable(entries, func(i, j int) bool {
  159. if entries[i].sortIndex != entries[j].sortIndex {
  160. return entries[i].sortIndex < entries[j].sortIndex
  161. }
  162. if entries[i].kind != entries[j].kind {
  163. return entries[i].kind < entries[j].kind
  164. }
  165. return entries[i].id < entries[j].id
  166. })
  167. var configArray []json_util.RawMessage
  168. for _, entry := range entries {
  169. configArray = append(configArray, entry.configs...)
  170. }
  171. for _, ext := range externalLinks {
  172. if ext.Enable {
  173. hasEnabledClient = true
  174. }
  175. if !ext.Active {
  176. seenEmails[ext.Email] = struct{}{}
  177. hasInactiveExternal = true
  178. continue
  179. }
  180. for _, el := range expandEntry(ext) {
  181. outbound := parsedExternalOutbound(el.Link)
  182. if outbound == nil {
  183. continue
  184. }
  185. seenEmails[ext.Email] = struct{}{}
  186. remark := el.Name
  187. if remark == "" {
  188. remark = ext.Email
  189. }
  190. newOutbounds := []json_util.RawMessage{outbound}
  191. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  192. newConfigJson := make(map[string]any)
  193. maps.Copy(newConfigJson, s.bakedTemplate())
  194. newConfigJson["outbounds"] = newOutbounds
  195. newConfigJson["remarks"] = remark
  196. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  197. configArray = append(configArray, newConfig)
  198. }
  199. }
  200. if len(configArray) == 0 && !hasInactiveExternal {
  201. return "", "", nil
  202. }
  203. emails := make([]string, 0, len(seenEmails))
  204. for e := range seenEmails {
  205. emails = append(emails, e)
  206. }
  207. slices.Sort(emails)
  208. traffic, _ := subReq.AggregateTrafficByEmails(emails)
  209. traffic.Enable = hasEnabledClient
  210. header = subReq.subscriptionUserinfo(traffic)
  211. if mode, remark := subReq.resolveInfoNodeRemark(subId, emails, traffic, len(configArray) > 0); mode != infoNodeNone {
  212. dummyConfig := s.genDummySocksConfig(remark)
  213. if mode == infoNodeExpired || mode == infoNodeDepleted {
  214. configArray = []json_util.RawMessage{dummyConfig}
  215. } else {
  216. configArray = append([]json_util.RawMessage{dummyConfig}, configArray...)
  217. }
  218. }
  219. if len(configArray) == 0 {
  220. return "", header, nil
  221. }
  222. var finalJson []byte
  223. if len(configArray) == 1 && !alwaysReturnArray {
  224. finalJson, _ = json.MarshalIndent(configArray[0], "", " ")
  225. } else {
  226. finalJson, _ = json.MarshalIndent(configArray, "", " ")
  227. }
  228. return string(finalJson), header, nil
  229. }
  230. // subConfigEntry is one ordered block of the JSON subscription: an inbound's
  231. // configs (kind 0) or a balancer config (kind 1).
  232. type subConfigEntry struct {
  233. sortIndex int
  234. kind int
  235. id int
  236. configs []json_util.RawMessage
  237. }
  238. const (
  239. subBalancerTag = "balancer"
  240. subBalancerProbeURL = "https://www.google.com/generate_204"
  241. )
  242. // subBalancerObservatoryConfig is the panel-wide burstObservatory ping config
  243. // emitted into every client-side balancer doc (subJsonObservatory setting).
  244. type subBalancerObservatoryConfig struct {
  245. Destination string `json:"destination"`
  246. Connectivity string `json:"connectivity"`
  247. Interval string `json:"interval"`
  248. Sampling int `json:"sampling"`
  249. Timeout string `json:"timeout"`
  250. HTTPMethod string `json:"httpMethod"`
  251. }
  252. func defaultSubBalancerObservatoryConfig() subBalancerObservatoryConfig {
  253. return subBalancerObservatoryConfig{
  254. Destination: subBalancerProbeURL,
  255. Connectivity: "",
  256. Interval: "1m",
  257. Sampling: 2,
  258. Timeout: "5s",
  259. HTTPMethod: "HEAD",
  260. }
  261. }
  262. // SetObservatoryConfig overrides defaults from the panel JSON setting. An empty
  263. // cfg keeps all defaults; invalid values fall back with a warning, never panic.
  264. func (s *SubJsonService) SetObservatoryConfig(cfg string) {
  265. s.observatory = defaultSubBalancerObservatoryConfig()
  266. if cfg == "" {
  267. return
  268. }
  269. var parsed subBalancerObservatoryConfig
  270. if err := json.Unmarshal([]byte(cfg), &parsed); err != nil {
  271. logger.Warningf("subJsonObservatory: invalid JSON %q, using defaults: %v", cfg, err)
  272. return
  273. }
  274. if parsed.Destination != "" {
  275. if validProbeURL(parsed.Destination) {
  276. s.observatory.Destination = parsed.Destination
  277. } else {
  278. logger.Warningf("subJsonObservatory: invalid destination %q, keeping default %q", parsed.Destination, s.observatory.Destination)
  279. }
  280. }
  281. if parsed.Connectivity != "" {
  282. if validProbeURL(parsed.Connectivity) {
  283. s.observatory.Connectivity = parsed.Connectivity
  284. } else {
  285. logger.Warningf("subJsonObservatory: invalid connectivity %q, keeping default (skip)", parsed.Connectivity)
  286. }
  287. }
  288. if parsed.Interval != "" {
  289. if _, err := time.ParseDuration(parsed.Interval); err == nil {
  290. s.observatory.Interval = parsed.Interval
  291. } else {
  292. logger.Warningf("subJsonObservatory: invalid interval %q, keeping default %q", parsed.Interval, s.observatory.Interval)
  293. }
  294. }
  295. if parsed.Sampling > 0 {
  296. s.observatory.Sampling = parsed.Sampling
  297. }
  298. if parsed.Timeout != "" {
  299. if _, err := time.ParseDuration(parsed.Timeout); err == nil {
  300. s.observatory.Timeout = parsed.Timeout
  301. } else {
  302. logger.Warningf("subJsonObservatory: invalid timeout %q, keeping default %q", parsed.Timeout, s.observatory.Timeout)
  303. }
  304. }
  305. if parsed.HTTPMethod == "HEAD" || parsed.HTTPMethod == "GET" {
  306. s.observatory.HTTPMethod = parsed.HTTPMethod
  307. }
  308. }
  309. // validProbeURL accepts only absolute http(s) URLs so a malformed probe or
  310. // connectivity value can't slip into the emitted burstObservatory.
  311. func validProbeURL(s string) bool {
  312. u, err := url.Parse(s)
  313. if err != nil || u == nil {
  314. return false
  315. }
  316. return u.Scheme == "http" || u.Scheme == "https"
  317. }
  318. func (s *SubJsonService) balancerObservatory(prefix string) map[string]any {
  319. o := s.observatory
  320. return map[string]any{
  321. "subjectSelector": []string{prefix},
  322. "pingConfig": map[string]any{
  323. "destination": o.Destination,
  324. "connectivity": o.Connectivity,
  325. "interval": o.Interval,
  326. "sampling": o.Sampling,
  327. "timeout": o.Timeout,
  328. "httpMethod": o.HTTPMethod,
  329. },
  330. }
  331. }
  332. // appendBalancerEntries appends one entry per enabled balancer that has at
  333. // least one member outbound among the inbound entries.
  334. func (s *SubJsonService) appendBalancerEntries(entries []subConfigEntry) []subConfigEntry {
  335. balancers := getEnabledSubBalancers()
  336. if len(balancers) == 0 {
  337. return entries
  338. }
  339. // Pre-pass: pull each inbound doc's proxy outbound once so every balancer
  340. // reuses it instead of re-unmarshalling the whole document per balancer.
  341. entryProxies := make([][]map[string]any, len(entries))
  342. for i, entry := range entries {
  343. if entry.kind != 0 {
  344. continue
  345. }
  346. for _, config := range entry.configs {
  347. if proxy := extractProxyOutbound(config); proxy != nil {
  348. entryProxies[i] = append(entryProxies[i], proxy)
  349. }
  350. }
  351. }
  352. for i := range balancers {
  353. config := s.buildBalancerConfig(&balancers[i], entries, entryProxies)
  354. if config == nil {
  355. continue
  356. }
  357. entries = append(entries, subConfigEntry{
  358. sortIndex: balancers[i].SortOrder,
  359. kind: 1,
  360. id: balancers[i].Id,
  361. configs: []json_util.RawMessage{config},
  362. })
  363. }
  364. return entries
  365. }
  366. // extractProxyOutbound returns the first outbound of a document when it is the
  367. // proxy (tag == "proxy"), else nil — the only member shape a balancer retags.
  368. func extractProxyOutbound(config json_util.RawMessage) map[string]any {
  369. var doc map[string]any
  370. if json.Unmarshal(config, &doc) != nil {
  371. return nil
  372. }
  373. outbounds, _ := doc["outbounds"].([]any)
  374. if len(outbounds) == 0 {
  375. return nil
  376. }
  377. outbound, _ := outbounds[0].(map[string]any)
  378. if outbound == nil || outbound["tag"] != "proxy" {
  379. return nil
  380. }
  381. return outbound
  382. }
  383. func getEnabledSubBalancers() []model.SubBalancer {
  384. var balancers []model.SubBalancer
  385. if err := database.GetDB().Model(&model.SubBalancer{}).
  386. Where("enabled = ?", true).
  387. Order("sort_order asc, id asc").Find(&balancers).Error; err != nil {
  388. logger.Error("SubJsonService - getEnabledSubBalancers:", err)
  389. return nil
  390. }
  391. return balancers
  392. }
  393. // Suffix by proxy protocol, not transport network — a vmess/tcp member used to
  394. // be mislabelled "vless".
  395. func balancerMemberSuffix(protocol string) string {
  396. if protocol == "" {
  397. return "other"
  398. }
  399. return protocol
  400. }
  401. // balMember is one retagged member outbound and the inbound it came from.
  402. type balMember struct {
  403. tag string
  404. inboundId int
  405. }
  406. // leastLoadCosts builds xray's static strategy costs: higher value = picked
  407. // less often; nil unless a member carries an explicit weight (all-1.0 bloat).
  408. func leastLoadCosts(balancer *model.SubBalancer, members []balMember) []any {
  409. if balancer.Strategy != "leastLoad" || len(members) == 0 || len(balancer.MemberWeights) == 0 {
  410. return nil
  411. }
  412. costs := make([]any, 0, len(members))
  413. configured := false
  414. for _, m := range members {
  415. value := 1.0
  416. if weight, ok := balancer.MemberWeights[m.inboundId]; ok && weight > 0 {
  417. value = weight
  418. configured = true
  419. }
  420. // Anchored regexp: plain cost matching is substring-based in xray, so
  421. // an unanchored "bal-1-vless" would also swallow "bal-1-vless-2".
  422. costs = append(costs, map[string]any{
  423. "regexp": true,
  424. "match": "^" + m.tag + "$",
  425. "value": value,
  426. })
  427. }
  428. if !configured {
  429. return nil
  430. }
  431. return costs
  432. }
  433. // buildBalancerConfig assembles the balancer profile: members retagged under a
  434. // per-balancer prefix, a routing.balancers entry, and (for leastPing/leastLoad) an observatory.
  435. func (s *SubJsonService) buildBalancerConfig(balancer *model.SubBalancer, entries []subConfigEntry, entryProxies [][]map[string]any) json_util.RawMessage {
  436. prefix := fmt.Sprintf("bal-%d-", balancer.Id)
  437. usedTags := make(map[string]bool)
  438. var proxies []json_util.RawMessage
  439. // Members in emission order with their owning inbound, so costs[] can
  440. // reference the exact retagged tags assigned here.
  441. var members []balMember
  442. var firstTag string
  443. // entryProxies is the pre-extracted proxy outbounds per entry; kind!=0 rows
  444. // have none. Clone before retagging so the cached map stays reusable.
  445. for i, entry := range entries {
  446. if entry.kind != 0 || !slices.Contains(balancer.InboundIds, entry.id) {
  447. continue
  448. }
  449. for _, outbound := range entryProxies[i] {
  450. protocol, _ := outbound["protocol"].(string)
  451. base := prefix + balancerMemberSuffix(protocol)
  452. tag := base
  453. for suffix := 2; usedTags[tag]; suffix++ {
  454. tag = fmt.Sprintf("%s-%d", base, suffix)
  455. }
  456. usedTags[tag] = true
  457. member := maps.Clone(outbound)
  458. member["tag"] = tag
  459. if raw, err := json.MarshalIndent(member, "", " "); err == nil {
  460. members = append(members, balMember{tag: tag, inboundId: entry.id})
  461. if firstTag == "" {
  462. firstTag = tag
  463. }
  464. proxies = append(proxies, raw)
  465. }
  466. }
  467. }
  468. if len(proxies) == 0 {
  469. return nil
  470. }
  471. outbounds := append([]json_util.RawMessage{}, proxies...)
  472. outbounds = append(outbounds, s.defaultOutbounds...)
  473. // One template per document: two resolves could straddle a profile refresh
  474. // and pair this document's dns with the other revision's routing.
  475. template := s.bakedTemplate()
  476. // Clone the shared routing subtree (and each rule map) before pointing
  477. // rules at the balancer.
  478. baseRouting, _ := template["routing"].(map[string]any)
  479. routing := make(map[string]any, len(baseRouting)+1)
  480. maps.Copy(routing, baseRouting)
  481. baseRules, _ := baseRouting["rules"].([]any)
  482. rules := make([]any, 0, len(baseRules)+1)
  483. for _, rule := range baseRules {
  484. ruleMap, ok := rule.(map[string]any)
  485. if !ok {
  486. rules = append(rules, rule)
  487. continue
  488. }
  489. ruleMap = maps.Clone(ruleMap)
  490. if ruleMap["outboundTag"] == "proxy" {
  491. delete(ruleMap, "outboundTag")
  492. ruleMap["balancerTag"] = subBalancerTag
  493. }
  494. rules = append(rules, ruleMap)
  495. }
  496. routing["rules"] = rules
  497. isObservatory := balancer.Strategy == "leastPing" || balancer.Strategy == "leastLoad"
  498. strategyEntry := map[string]any{"type": balancer.Strategy}
  499. if costs := leastLoadCosts(balancer, members); costs != nil {
  500. strategyEntry["settings"] = map[string]any{"costs": costs}
  501. }
  502. balancerEntry := map[string]any{
  503. "tag": subBalancerTag,
  504. "selector": []string{prefix},
  505. "strategy": strategyEntry,
  506. }
  507. if isObservatory && firstTag != "" {
  508. // With all probes failing, route to the first member instead of
  509. // failing dispatch.
  510. balancerEntry["fallbackTag"] = firstTag
  511. }
  512. routing["balancers"] = []any{balancerEntry}
  513. newConfigJson := make(map[string]any, len(template)+2)
  514. maps.Copy(newConfigJson, template)
  515. newConfigJson["outbounds"] = outbounds
  516. newConfigJson["remarks"] = balancer.Remark
  517. newConfigJson["routing"] = routing
  518. // leastPing/leastLoad require a burst observatory (Xray refuses to start
  519. // them without one); fallbackTag above covers the probe-outage case.
  520. if isObservatory {
  521. newConfigJson["burstObservatory"] = s.balancerObservatory(prefix)
  522. }
  523. config, _ := json.MarshalIndent(newConfigJson, "", " ")
  524. return config
  525. }
  526. func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage {
  527. var newJsonArray []json_util.RawMessage
  528. stream := s.streamData(inbound.StreamSettings, subKey(client))
  529. // When externalProxy is empty the JSON config falls back to a
  530. // synthetic one whose `dest` is the host the client connects to.
  531. // For node-managed inbounds we want the node's address — request
  532. // host won't reach the right xray. resolveInboundAddress already
  533. // implements the node→subscriber-host fallback chain.
  534. defaultDest := subReq.resolveInboundAddress(inbound)
  535. if defaultDest == "" {
  536. defaultDest = host
  537. }
  538. // Per-inbound xmux takes precedence over the global subJsonMux.
  539. // When xmux is present inside xhttpSettings, XHTTP multiplexing
  540. // is handled by xmux — don't also set the legacy outbound.Mux.
  541. mux := s.mux
  542. if xhttp, ok := stream["xhttpSettings"].(map[string]any); ok {
  543. if _, hasXmux := xhttp["xmux"]; hasXmux {
  544. mux = ""
  545. }
  546. }
  547. externalProxies, ok := stream["externalProxy"].([]any)
  548. hasExternalProxy := ok && len(externalProxies) > 0
  549. if !hasExternalProxy {
  550. externalProxies = []any{
  551. map[string]any{
  552. "forceTls": "same",
  553. "dest": defaultDest,
  554. "port": float64(inbound.Port),
  555. "remark": "",
  556. },
  557. }
  558. }
  559. delete(stream, "externalProxy")
  560. network, _ := stream["network"].(string)
  561. for _, ep := range externalProxies {
  562. extPrxy, ok := ep.(map[string]any)
  563. if !ok {
  564. continue
  565. }
  566. // Expand the host's {{VAR}} remark template for this client (no-op for
  567. // the synthetic/legacy entry) before it's used as the config remark.
  568. subReq.renderHostRemark(inbound, client, extPrxy, network)
  569. inbound.Listen, _ = extPrxy["dest"].(string)
  570. if port, ok := extPrxy["port"].(float64); ok {
  571. inbound.Port = int(port)
  572. }
  573. newStream := cloneStreamForExternalProxy(stream)
  574. forceTls, _ := extPrxy["forceTls"].(string)
  575. switch forceTls {
  576. case "tls":
  577. if newStream["security"] != "tls" {
  578. newStream["security"] = "tls"
  579. newStream["tlsSettings"] = map[string]any{}
  580. }
  581. case "none":
  582. if newStream["security"] != "none" {
  583. newStream["security"] = "none"
  584. delete(newStream, "tlsSettings")
  585. }
  586. }
  587. security, _ := newStream["security"].(string)
  588. if hasExternalProxy {
  589. applyExternalProxyTLSToStream(extPrxy, newStream, security)
  590. }
  591. applyHostStreamOverrides(extPrxy, newStream)
  592. streamSettings, _ := json.MarshalIndent(newStream, "", " ")
  593. hostMux := hostMuxOverride(extPrxy)
  594. var newOutbounds []json_util.RawMessage
  595. switch inbound.Protocol {
  596. case "vmess":
  597. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client, jsonMux(mux, hostMux)))
  598. case "vless":
  599. vc := client
  600. vc.ID = applyVlessRoute(client.ID, hostVlessRoute(extPrxy))
  601. // Same gate the raw link and the Clash proxy apply: a flow left
  602. // over from a transport Vision supported produces an outbound
  603. // xray refuses to start.
  604. newNetwork, _ := newStream["network"].(string)
  605. if vc.Flow != "" && !vlessFlowAllowed(newNetwork, security, subReq.linkSettings(inbound)) {
  606. vc.Flow = ""
  607. }
  608. newOutbounds = append(newOutbounds, s.genVless(subReq, inbound, streamSettings, vc, jsonMux(mux, hostMux)))
  609. case "trojan", "shadowsocks":
  610. newOutbounds = append(newOutbounds, s.genServer(subReq, inbound, streamSettings, client, jsonMux(mux, hostMux)))
  611. case "hysteria":
  612. newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client, jsonMux(mux, hostMux)))
  613. case "wireguard":
  614. wgOutbound := s.genWireguard(inbound, client)
  615. if wgOutbound == nil {
  616. continue
  617. }
  618. newOutbounds = append(newOutbounds, wgOutbound)
  619. case "amneziawg", "tuic":
  620. continue
  621. }
  622. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  623. newConfigJson := make(map[string]any)
  624. maps.Copy(newConfigJson, s.bakedTemplate())
  625. transport, _ := newStream["network"].(string)
  626. newConfigJson["outbounds"] = newOutbounds
  627. newConfigJson["remarks"] = subReq.endpointRemark(inbound, client.Email, extPrxy, transport)
  628. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  629. newJsonArray = append(newJsonArray, newConfig)
  630. }
  631. return newJsonArray
  632. }
  633. func (s *SubJsonService) streamData(stream string, clientKey string) map[string]any {
  634. var streamSettings map[string]any
  635. if err := json.Unmarshal([]byte(stream), &streamSettings); err != nil || streamSettings == nil {
  636. streamSettings = map[string]any{}
  637. }
  638. security, _ := streamSettings["security"].(string)
  639. switch security {
  640. case "tls":
  641. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  642. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  643. } else {
  644. delete(streamSettings, "tlsSettings")
  645. }
  646. case "reality":
  647. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  648. streamSettings["realitySettings"] = s.realityData(realitySettings, clientKey)
  649. } else {
  650. delete(streamSettings, "realitySettings")
  651. }
  652. }
  653. delete(streamSettings, "sockopt")
  654. if s.finalMask != "" {
  655. s.applyGlobalFinalMask(streamSettings)
  656. }
  657. // remove proxy protocol
  658. network, _ := streamSettings["network"].(string)
  659. switch network {
  660. case "tcp":
  661. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  662. case "ws":
  663. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  664. case "httpupgrade":
  665. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  666. case "xhttp":
  667. streamSettings["xhttpSettings"] = s.removeAcceptProxy(streamSettings["xhttpSettings"])
  668. if xhttp, ok := streamSettings["xhttpSettings"].(map[string]any); ok {
  669. delete(xhttp, "noSSEHeader")
  670. delete(xhttp, "scMaxBufferedPosts")
  671. delete(xhttp, "scStreamUpServerSecs")
  672. delete(xhttp, "serverMaxHeaderBytes")
  673. // Values matching xray-core's own defaults stay off the wire:
  674. // old panels seeded them into every stored config and the
  675. // literal scMinPostsIntervalMs=30 is a DPI fingerprint (#5141).
  676. if v, _ := xhttp["scMaxEachPostBytes"].(string); v == "" || v == "1000000" {
  677. delete(xhttp, "scMaxEachPostBytes")
  678. }
  679. if v, _ := xhttp["scMinPostsIntervalMs"].(string); v == "" || v == "30" {
  680. delete(xhttp, "scMinPostsIntervalMs")
  681. }
  682. }
  683. }
  684. return streamSettings
  685. }
  686. func (s *SubJsonService) applyGlobalFinalMask(streamSettings map[string]any) {
  687. var fm map[string]any
  688. if err := json.Unmarshal([]byte(s.finalMask), &fm); err != nil || len(fm) == 0 {
  689. return
  690. }
  691. merged := mergeFinalMask(streamSettings["finalmask"], fm)
  692. if len(merged) > 0 {
  693. streamSettings["finalmask"] = merged
  694. }
  695. }
  696. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  697. netSettings, ok := setting.(map[string]any)
  698. if ok {
  699. delete(netSettings, "acceptProxyProtocol")
  700. }
  701. return netSettings
  702. }
  703. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  704. tlsData := make(map[string]any, 1)
  705. tlsClientSettings, _ := tData["settings"].(map[string]any)
  706. tlsData["serverName"] = tData["serverName"]
  707. tlsData["alpn"] = tData["alpn"]
  708. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  709. tlsData["fingerprint"] = fingerprint
  710. }
  711. if cs, ok := tData["cipherSuites"].(string); ok && cs != "" {
  712. tlsData["cipherSuites"] = cs
  713. }
  714. if ech, ok := tlsClientSettings["echConfigList"].(string); ok && ech != "" {
  715. tlsData["echConfigList"] = ech
  716. }
  717. if vcn, ok := verifyPeerCertByNameValue(tlsClientSettings); ok {
  718. tlsData["verifyPeerCertByName"] = vcn
  719. }
  720. // xray-core now parses pinnedPeerCertSha256 as a comma-separated string, not
  721. // an array; emit the joined form so v2ray clients can import the config (#5401).
  722. if pins, ok := pinnedSha256List(tlsClientSettings); ok {
  723. tlsData["pinnedPeerCertSha256"] = strings.Join(pins, ",")
  724. }
  725. return tlsData
  726. }
  727. func (s *SubJsonService) realityData(rData map[string]any, clientKey string) map[string]any {
  728. rltyData := make(map[string]any, 1)
  729. rltyClientSettings, _ := rData["settings"].(map[string]any)
  730. rltyData["show"] = false
  731. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  732. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  733. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  734. seed, _ := rltyClientSettings["spiderX"].(string)
  735. rltyData["spiderX"] = deriveSpiderX(seed, clientKey)
  736. shortIds, ok := rData["shortIds"].([]any)
  737. if ok && len(shortIds) > 0 {
  738. rltyData["shortId"], _ = shortIds[random.Num(len(shortIds))].(string)
  739. } else {
  740. rltyData["shortId"] = ""
  741. }
  742. serverNames, ok := rData["serverNames"].([]any)
  743. if ok && len(serverNames) > 0 {
  744. rltyData["serverName"], _ = serverNames[random.Num(len(serverNames))].(string)
  745. } else {
  746. rltyData["serverName"] = ""
  747. }
  748. return rltyData
  749. }
  750. // jsonMux picks the per-host mux override when present, else the global mux.
  751. func jsonMux(global, override string) string {
  752. if override != "" {
  753. return override
  754. }
  755. return global
  756. }
  757. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  758. outbound := Outbound{
  759. Protocol: string(inbound.Protocol),
  760. Tag: "proxy",
  761. }
  762. if mux != "" {
  763. outbound.Mux = json_util.RawMessage(mux)
  764. }
  765. outbound.StreamSettings = streamSettings
  766. security := normalizeVmessSecurity(client.Security)
  767. outbound.Settings = map[string]any{
  768. "address": inbound.Listen,
  769. "port": inbound.Port,
  770. "id": client.ID,
  771. "security": security,
  772. "level": 8,
  773. }
  774. result, _ := json.MarshalIndent(outbound, "", " ")
  775. return result
  776. }
  777. func (s *SubJsonService) genVless(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  778. outbound := Outbound{
  779. Protocol: string(inbound.Protocol),
  780. Tag: "proxy",
  781. }
  782. if mux != "" {
  783. outbound.Mux = json_util.RawMessage(mux)
  784. }
  785. outbound.StreamSettings = streamSettings
  786. // Add encryption for VLESS outbound from inbound settings
  787. inboundSettings := subReq.linkSettings(inbound)
  788. encryption, _ := inboundSettings["encryption"].(string)
  789. settings := map[string]any{
  790. "address": inbound.Listen,
  791. "port": inbound.Port,
  792. "id": client.ID,
  793. "encryption": encryption,
  794. "level": 8,
  795. }
  796. if client.Flow != "" && !inbound.DisableFlow {
  797. settings["flow"] = client.Flow
  798. outbound.Mux = muxWithoutTCP(mux)
  799. }
  800. outbound.Settings = settings
  801. result, _ := json.MarshalIndent(outbound, "", " ")
  802. return result
  803. }
  804. // XTLS flows reject TCP mux.cool ("unexpected network TCP"); concurrency -1
  805. // turns only that off and keeps the XUDP keys (Xray reads them under enabled).
  806. func muxWithoutTCP(mux string) json_util.RawMessage {
  807. if mux == "" {
  808. return nil
  809. }
  810. var m map[string]any
  811. if err := json.Unmarshal([]byte(mux), &m); err != nil || m == nil {
  812. return nil
  813. }
  814. m["concurrency"] = -1
  815. out, err := json.Marshal(m)
  816. if err != nil {
  817. return nil
  818. }
  819. return json_util.RawMessage(out)
  820. }
  821. func (s *SubJsonService) genServer(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  822. outbound := Outbound{}
  823. serverData := make([]ServerSetting, 1)
  824. serverData[0] = ServerSetting{
  825. Address: inbound.Listen,
  826. Port: inbound.Port,
  827. Level: 8,
  828. Password: client.Password,
  829. }
  830. if inbound.Protocol == model.Shadowsocks {
  831. inboundSettings := subReq.linkSettings(inbound)
  832. method, _ := inboundSettings["method"].(string)
  833. serverData[0].Method = method
  834. // server password in multi-user 2022 protocols
  835. if strings.HasPrefix(method, "2022") {
  836. if serverPassword, ok := inboundSettings["password"].(string); ok {
  837. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  838. }
  839. }
  840. }
  841. outbound.Protocol = string(inbound.Protocol)
  842. outbound.Tag = "proxy"
  843. if mux != "" {
  844. outbound.Mux = json_util.RawMessage(mux)
  845. }
  846. outbound.StreamSettings = streamSettings
  847. // Wrap the endpoint in a "servers" array (the standard Xray schema for
  848. // Shadowsocks/Trojan outbounds). The flat top-level form only parses on very
  849. // recent xray-core; older bundled cores (e.g. in v2rayN) reject it, so SS
  850. // links fail to connect. See genVnext/genVless for the VMess/VLESS shape.
  851. server := map[string]any{
  852. "address": serverData[0].Address,
  853. "port": serverData[0].Port,
  854. "password": serverData[0].Password,
  855. "level": 8,
  856. }
  857. if inbound.Protocol == model.Shadowsocks {
  858. server["method"] = serverData[0].Method
  859. }
  860. outbound.Settings = map[string]any{
  861. "servers": []any{server},
  862. }
  863. result, _ := json.MarshalIndent(outbound, "", " ")
  864. return result
  865. }
  866. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client, mux string) json_util.RawMessage {
  867. outbound := Outbound{
  868. Protocol: string(inbound.Protocol),
  869. Tag: "proxy",
  870. }
  871. if mux != "" {
  872. outbound.Mux = json_util.RawMessage(mux)
  873. }
  874. var settings, stream map[string]any
  875. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  876. version, _ := settings["version"].(float64)
  877. outbound.Settings = map[string]any{
  878. "version": int(version),
  879. "address": inbound.Listen,
  880. "port": inbound.Port,
  881. }
  882. _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  883. hyStream, _ := stream["hysteriaSettings"].(map[string]any)
  884. outHyStream := map[string]any{
  885. "version": int(version),
  886. "auth": client.Auth,
  887. }
  888. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  889. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  890. }
  891. if masquerade, ok := hyStream["masquerade"].(map[string]any); ok {
  892. outHyStream["masquerade"] = masquerade
  893. }
  894. newStream["hysteriaSettings"] = outHyStream
  895. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  896. newStream["finalmask"] = mergeFinalMask(newStream["finalmask"], finalmask)
  897. }
  898. newStream["network"] = "hysteria"
  899. newStream["security"] = "tls"
  900. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  901. result, _ := json.MarshalIndent(outbound, "", " ")
  902. return result
  903. }
  904. // genWireguard builds an Xray wireguard outbound for a native WireGuard inbound,
  905. // mirroring genWireguardLink: the peer public key is derived from the inbound
  906. // secretKey, the client owns the private key / tunnel address / pre-shared key,
  907. // and the peer routes the full tunnel. Returns nil when the client has no key.
  908. func (s *SubJsonService) genWireguard(inbound *model.Inbound, client model.Client) json_util.RawMessage {
  909. if client.PrivateKey == "" {
  910. return nil
  911. }
  912. var inboundSettings map[string]any
  913. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  914. secretKey, _ := inboundSettings["secretKey"].(string)
  915. peer := map[string]any{
  916. "endpoint": joinHostPort(inbound.Listen, inbound.Port),
  917. "allowedIPs": []string{"0.0.0.0/0", "::/0"},
  918. }
  919. if secretKey != "" {
  920. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  921. peer["publicKey"] = pub
  922. }
  923. }
  924. if client.PreSharedKey != "" {
  925. peer["preSharedKey"] = client.PreSharedKey
  926. }
  927. if ka := client.KeepAliveSeconds(); ka > 0 {
  928. peer["keepAlive"] = ka
  929. }
  930. settings := map[string]any{
  931. "secretKey": client.PrivateKey,
  932. "peers": []any{peer},
  933. }
  934. if len(client.AllowedIPs) > 0 {
  935. settings["address"] = client.AllowedIPs
  936. }
  937. if mtu, ok := inboundSettings["mtu"].(float64); ok && mtu > 0 {
  938. settings["mtu"] = int(mtu)
  939. }
  940. outbound := map[string]any{
  941. "protocol": string(inbound.Protocol),
  942. "tag": "proxy",
  943. "settings": settings,
  944. }
  945. result, _ := json.MarshalIndent(outbound, "", " ")
  946. return result
  947. }
  948. func (s *SubJsonService) genDummySocksConfig(remark string) json_util.RawMessage {
  949. outbound := map[string]any{
  950. "protocol": "socks",
  951. "tag": "proxy",
  952. "settings": map[string]any{
  953. "servers": []any{
  954. map[string]any{
  955. "address": "127.0.0.1",
  956. "port": 1080,
  957. },
  958. },
  959. },
  960. }
  961. rawOutbound, _ := json.Marshal(outbound)
  962. newOutbounds := []json_util.RawMessage{rawOutbound}
  963. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  964. newConfigJson := make(map[string]any)
  965. maps.Copy(newConfigJson, s.configJson)
  966. if s.dnsBlock != nil {
  967. newConfigJson["dns"] = s.dnsBlock
  968. }
  969. newConfigJson["outbounds"] = newOutbounds
  970. newConfigJson["remarks"] = remark
  971. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  972. return newConfig
  973. }
  974. func mergeFinalMask(base any, extra map[string]any) map[string]any {
  975. merged := map[string]any{}
  976. if baseMap, ok := base.(map[string]any); ok {
  977. for key, value := range baseMap {
  978. switch key {
  979. case "tcp", "udp":
  980. if masks, ok := value.([]any); ok {
  981. merged[key] = append([]any(nil), masks...)
  982. }
  983. default:
  984. merged[key] = value
  985. }
  986. }
  987. }
  988. for key, value := range extra {
  989. switch key {
  990. case "tcp", "udp":
  991. baseMasks, _ := merged[key].([]any)
  992. extraMasks, _ := value.([]any)
  993. if len(extraMasks) > 0 {
  994. merged[key] = append(baseMasks, extraMasks...)
  995. }
  996. case "quicParams":
  997. if _, exists := merged[key]; !exists {
  998. merged[key] = value
  999. }
  1000. default:
  1001. merged[key] = value
  1002. }
  1003. }
  1004. return merged
  1005. }
  1006. type Outbound struct {
  1007. Protocol string `json:"protocol"`
  1008. Tag string `json:"tag"`
  1009. StreamSettings json_util.RawMessage `json:"streamSettings"`
  1010. Mux json_util.RawMessage `json:"mux,omitempty"`
  1011. Settings map[string]any `json:"settings,omitempty"`
  1012. }
  1013. type ServerSetting struct {
  1014. Password string `json:"password"`
  1015. Level int `json:"level"`
  1016. Address string `json:"address"`
  1017. Port int `json:"port"`
  1018. Flow string `json:"flow,omitempty"`
  1019. Method string `json:"method,omitempty"`
  1020. }