1
0

json_service.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  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. if finalmask, ok := newStream["finalmask"].(map[string]any); ok {
  593. newStream["finalmask"] = withLegacyFragmentRanges(finalmask)
  594. }
  595. streamSettings, _ := json.MarshalIndent(newStream, "", " ")
  596. hostMux := hostMuxOverride(extPrxy)
  597. var newOutbounds []json_util.RawMessage
  598. switch inbound.Protocol {
  599. case "vmess":
  600. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client, jsonMux(mux, hostMux)))
  601. case "vless":
  602. vc := client
  603. vc.ID = applyVlessRoute(client.ID, hostVlessRoute(extPrxy))
  604. // Same gate the raw link and the Clash proxy apply: a flow left
  605. // over from a transport Vision supported produces an outbound
  606. // xray refuses to start.
  607. newNetwork, _ := newStream["network"].(string)
  608. if vc.Flow != "" && !vlessFlowAllowed(newNetwork, security, subReq.linkSettings(inbound)) {
  609. vc.Flow = ""
  610. }
  611. newOutbounds = append(newOutbounds, s.genVless(subReq, inbound, streamSettings, vc, jsonMux(mux, hostMux)))
  612. case "trojan", "shadowsocks":
  613. newOutbounds = append(newOutbounds, s.genServer(subReq, inbound, streamSettings, client, jsonMux(mux, hostMux)))
  614. case "hysteria":
  615. newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client, jsonMux(mux, hostMux)))
  616. case "wireguard":
  617. wgOutbound := s.genWireguard(inbound, client)
  618. if wgOutbound == nil {
  619. continue
  620. }
  621. newOutbounds = append(newOutbounds, wgOutbound)
  622. case "amneziawg", "tuic":
  623. continue
  624. }
  625. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  626. newConfigJson := make(map[string]any)
  627. maps.Copy(newConfigJson, s.bakedTemplate())
  628. transport, _ := newStream["network"].(string)
  629. newConfigJson["outbounds"] = newOutbounds
  630. newConfigJson["remarks"] = subReq.endpointRemark(inbound, client.Email, extPrxy, transport)
  631. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  632. newJsonArray = append(newJsonArray, newConfig)
  633. }
  634. return newJsonArray
  635. }
  636. func (s *SubJsonService) streamData(stream string, clientKey string) map[string]any {
  637. var streamSettings map[string]any
  638. if err := json.Unmarshal([]byte(stream), &streamSettings); err != nil || streamSettings == nil {
  639. streamSettings = map[string]any{}
  640. }
  641. security, _ := streamSettings["security"].(string)
  642. switch security {
  643. case "tls":
  644. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  645. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  646. } else {
  647. delete(streamSettings, "tlsSettings")
  648. }
  649. case "reality":
  650. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  651. streamSettings["realitySettings"] = s.realityData(realitySettings, clientKey)
  652. } else {
  653. delete(streamSettings, "realitySettings")
  654. }
  655. }
  656. delete(streamSettings, "sockopt")
  657. if s.finalMask != "" {
  658. s.applyGlobalFinalMask(streamSettings)
  659. }
  660. // remove proxy protocol
  661. network, _ := streamSettings["network"].(string)
  662. switch network {
  663. case "tcp":
  664. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  665. case "ws":
  666. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  667. case "httpupgrade":
  668. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  669. case "xhttp":
  670. streamSettings["xhttpSettings"] = s.removeAcceptProxy(streamSettings["xhttpSettings"])
  671. if xhttp, ok := streamSettings["xhttpSettings"].(map[string]any); ok {
  672. delete(xhttp, "noSSEHeader")
  673. delete(xhttp, "scMaxBufferedPosts")
  674. delete(xhttp, "scStreamUpServerSecs")
  675. delete(xhttp, "serverMaxHeaderBytes")
  676. // Values matching xray-core's own defaults stay off the wire:
  677. // old panels seeded them into every stored config and the
  678. // literal scMinPostsIntervalMs=30 is a DPI fingerprint (#5141).
  679. if v, _ := xhttp["scMaxEachPostBytes"].(string); v == "" || v == "1000000" {
  680. delete(xhttp, "scMaxEachPostBytes")
  681. }
  682. if v, _ := xhttp["scMinPostsIntervalMs"].(string); v == "" || v == "30" {
  683. delete(xhttp, "scMinPostsIntervalMs")
  684. }
  685. }
  686. }
  687. return streamSettings
  688. }
  689. func (s *SubJsonService) applyGlobalFinalMask(streamSettings map[string]any) {
  690. var fm map[string]any
  691. if err := json.Unmarshal([]byte(s.finalMask), &fm); err != nil || len(fm) == 0 {
  692. return
  693. }
  694. merged := mergeFinalMask(streamSettings["finalmask"], fm)
  695. if len(merged) > 0 {
  696. streamSettings["finalmask"] = merged
  697. }
  698. }
  699. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  700. netSettings, ok := setting.(map[string]any)
  701. if ok {
  702. delete(netSettings, "acceptProxyProtocol")
  703. }
  704. return netSettings
  705. }
  706. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  707. tlsData := make(map[string]any, 1)
  708. tlsClientSettings, _ := tData["settings"].(map[string]any)
  709. tlsData["serverName"] = tData["serverName"]
  710. tlsData["alpn"] = tData["alpn"]
  711. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  712. tlsData["fingerprint"] = fingerprint
  713. }
  714. if cs, ok := tData["cipherSuites"].(string); ok && cs != "" {
  715. tlsData["cipherSuites"] = cs
  716. }
  717. if ech, ok := tlsClientSettings["echConfigList"].(string); ok && ech != "" {
  718. tlsData["echConfigList"] = ech
  719. }
  720. if vcn, ok := verifyPeerCertByNameValue(tlsClientSettings); ok {
  721. tlsData["verifyPeerCertByName"] = vcn
  722. }
  723. // xray-core now parses pinnedPeerCertSha256 as a comma-separated string, not
  724. // an array; emit the joined form so v2ray clients can import the config (#5401).
  725. if pins, ok := pinnedSha256List(tlsClientSettings); ok {
  726. tlsData["pinnedPeerCertSha256"] = strings.Join(pins, ",")
  727. }
  728. return tlsData
  729. }
  730. func (s *SubJsonService) realityData(rData map[string]any, clientKey string) map[string]any {
  731. rltyData := make(map[string]any, 1)
  732. rltyClientSettings, _ := rData["settings"].(map[string]any)
  733. rltyData["show"] = false
  734. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  735. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  736. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  737. seed, _ := rltyClientSettings["spiderX"].(string)
  738. rltyData["spiderX"] = deriveSpiderX(seed, clientKey)
  739. shortIds, ok := rData["shortIds"].([]any)
  740. if ok && len(shortIds) > 0 {
  741. rltyData["shortId"], _ = shortIds[random.Num(len(shortIds))].(string)
  742. } else {
  743. rltyData["shortId"] = ""
  744. }
  745. serverNames, ok := rData["serverNames"].([]any)
  746. if ok && len(serverNames) > 0 {
  747. rltyData["serverName"], _ = serverNames[random.Num(len(serverNames))].(string)
  748. } else {
  749. rltyData["serverName"] = ""
  750. }
  751. return rltyData
  752. }
  753. // jsonMux picks the per-host mux override when present, else the global mux.
  754. func jsonMux(global, override string) string {
  755. if override != "" {
  756. return override
  757. }
  758. return global
  759. }
  760. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  761. outbound := Outbound{
  762. Protocol: string(inbound.Protocol),
  763. Tag: "proxy",
  764. }
  765. if mux != "" {
  766. outbound.Mux = json_util.RawMessage(mux)
  767. }
  768. outbound.StreamSettings = streamSettings
  769. security := normalizeVmessSecurity(client.Security)
  770. outbound.Settings = map[string]any{
  771. "address": inbound.Listen,
  772. "port": inbound.Port,
  773. "id": client.ID,
  774. "security": security,
  775. "level": 8,
  776. }
  777. result, _ := json.MarshalIndent(outbound, "", " ")
  778. return result
  779. }
  780. func (s *SubJsonService) genVless(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  781. outbound := Outbound{
  782. Protocol: string(inbound.Protocol),
  783. Tag: "proxy",
  784. }
  785. if mux != "" {
  786. outbound.Mux = json_util.RawMessage(mux)
  787. }
  788. outbound.StreamSettings = streamSettings
  789. // Add encryption for VLESS outbound from inbound settings
  790. inboundSettings := subReq.linkSettings(inbound)
  791. encryption, _ := inboundSettings["encryption"].(string)
  792. settings := map[string]any{
  793. "address": inbound.Listen,
  794. "port": inbound.Port,
  795. "id": client.ID,
  796. "encryption": encryption,
  797. "level": 8,
  798. }
  799. if client.Flow != "" && !inbound.DisableFlow {
  800. settings["flow"] = client.Flow
  801. outbound.Mux = muxWithoutTCP(mux)
  802. }
  803. outbound.Settings = settings
  804. result, _ := json.MarshalIndent(outbound, "", " ")
  805. return result
  806. }
  807. // XTLS flows reject TCP mux.cool ("unexpected network TCP"); concurrency -1
  808. // turns only that off and keeps the XUDP keys (Xray reads them under enabled).
  809. func muxWithoutTCP(mux string) json_util.RawMessage {
  810. if mux == "" {
  811. return nil
  812. }
  813. var m map[string]any
  814. if err := json.Unmarshal([]byte(mux), &m); err != nil || m == nil {
  815. return nil
  816. }
  817. m["concurrency"] = -1
  818. out, err := json.Marshal(m)
  819. if err != nil {
  820. return nil
  821. }
  822. return json_util.RawMessage(out)
  823. }
  824. func (s *SubJsonService) genServer(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  825. outbound := Outbound{}
  826. serverData := make([]ServerSetting, 1)
  827. serverData[0] = ServerSetting{
  828. Address: inbound.Listen,
  829. Port: inbound.Port,
  830. Level: 8,
  831. Password: client.Password,
  832. }
  833. if inbound.Protocol == model.Shadowsocks {
  834. inboundSettings := subReq.linkSettings(inbound)
  835. method, _ := inboundSettings["method"].(string)
  836. serverData[0].Method = method
  837. // server password in multi-user 2022 protocols
  838. if strings.HasPrefix(method, "2022") {
  839. if serverPassword, ok := inboundSettings["password"].(string); ok {
  840. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  841. }
  842. }
  843. }
  844. outbound.Protocol = string(inbound.Protocol)
  845. outbound.Tag = "proxy"
  846. if mux != "" {
  847. outbound.Mux = json_util.RawMessage(mux)
  848. }
  849. outbound.StreamSettings = streamSettings
  850. // Wrap the endpoint in a "servers" array (the standard Xray schema for
  851. // Shadowsocks/Trojan outbounds). The flat top-level form only parses on very
  852. // recent xray-core; older bundled cores (e.g. in v2rayN) reject it, so SS
  853. // links fail to connect. See genVnext/genVless for the VMess/VLESS shape.
  854. server := map[string]any{
  855. "address": serverData[0].Address,
  856. "port": serverData[0].Port,
  857. "password": serverData[0].Password,
  858. "level": 8,
  859. }
  860. if inbound.Protocol == model.Shadowsocks {
  861. server["method"] = serverData[0].Method
  862. }
  863. outbound.Settings = map[string]any{
  864. "servers": []any{server},
  865. }
  866. result, _ := json.MarshalIndent(outbound, "", " ")
  867. return result
  868. }
  869. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client, mux string) json_util.RawMessage {
  870. outbound := Outbound{
  871. Protocol: string(inbound.Protocol),
  872. Tag: "proxy",
  873. }
  874. if mux != "" {
  875. outbound.Mux = json_util.RawMessage(mux)
  876. }
  877. var settings, stream map[string]any
  878. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  879. version, _ := settings["version"].(float64)
  880. outbound.Settings = map[string]any{
  881. "version": int(version),
  882. "address": inbound.Listen,
  883. "port": inbound.Port,
  884. }
  885. _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  886. hyStream, _ := stream["hysteriaSettings"].(map[string]any)
  887. outHyStream := map[string]any{
  888. "version": int(version),
  889. "auth": client.Auth,
  890. }
  891. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  892. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  893. }
  894. if masquerade, ok := hyStream["masquerade"].(map[string]any); ok {
  895. outHyStream["masquerade"] = masquerade
  896. }
  897. newStream["hysteriaSettings"] = outHyStream
  898. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  899. newStream["finalmask"] = mergeFinalMask(newStream["finalmask"], finalmask)
  900. }
  901. newStream["network"] = "hysteria"
  902. newStream["security"] = "tls"
  903. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  904. result, _ := json.MarshalIndent(outbound, "", " ")
  905. return result
  906. }
  907. // genWireguard builds an Xray wireguard outbound for a native WireGuard inbound,
  908. // mirroring genWireguardLink: the peer public key is derived from the inbound
  909. // secretKey, the client owns the private key / tunnel address / pre-shared key,
  910. // and the peer routes the full tunnel. Returns nil when the client has no key.
  911. func (s *SubJsonService) genWireguard(inbound *model.Inbound, client model.Client) json_util.RawMessage {
  912. if client.PrivateKey == "" {
  913. return nil
  914. }
  915. var inboundSettings map[string]any
  916. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  917. secretKey, _ := inboundSettings["secretKey"].(string)
  918. peer := map[string]any{
  919. "endpoint": joinHostPort(inbound.Listen, inbound.Port),
  920. "allowedIPs": []string{"0.0.0.0/0", "::/0"},
  921. }
  922. if secretKey != "" {
  923. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  924. peer["publicKey"] = pub
  925. }
  926. }
  927. if client.PreSharedKey != "" {
  928. peer["preSharedKey"] = client.PreSharedKey
  929. }
  930. if ka := client.KeepAliveSeconds(); ka > 0 {
  931. peer["keepAlive"] = ka
  932. }
  933. settings := map[string]any{
  934. "secretKey": client.PrivateKey,
  935. "peers": []any{peer},
  936. }
  937. if len(client.AllowedIPs) > 0 {
  938. settings["address"] = client.AllowedIPs
  939. }
  940. if mtu, ok := inboundSettings["mtu"].(float64); ok && mtu > 0 {
  941. settings["mtu"] = int(mtu)
  942. }
  943. outbound := map[string]any{
  944. "protocol": string(inbound.Protocol),
  945. "tag": "proxy",
  946. "settings": settings,
  947. }
  948. result, _ := json.MarshalIndent(outbound, "", " ")
  949. return result
  950. }
  951. func (s *SubJsonService) genDummySocksConfig(remark string) json_util.RawMessage {
  952. outbound := map[string]any{
  953. "protocol": "socks",
  954. "tag": "proxy",
  955. "settings": map[string]any{
  956. "servers": []any{
  957. map[string]any{
  958. "address": "127.0.0.1",
  959. "port": 1080,
  960. },
  961. },
  962. },
  963. }
  964. rawOutbound, _ := json.Marshal(outbound)
  965. newOutbounds := []json_util.RawMessage{rawOutbound}
  966. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  967. newConfigJson := make(map[string]any)
  968. maps.Copy(newConfigJson, s.configJson)
  969. if s.dnsBlock != nil {
  970. newConfigJson["dns"] = s.dnsBlock
  971. }
  972. newConfigJson["outbounds"] = newOutbounds
  973. newConfigJson["remarks"] = remark
  974. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  975. return newConfig
  976. }
  977. func mergeFinalMask(base any, extra map[string]any) map[string]any {
  978. merged := map[string]any{}
  979. if baseMap, ok := base.(map[string]any); ok {
  980. for key, value := range baseMap {
  981. switch key {
  982. case "tcp", "udp":
  983. if masks, ok := value.([]any); ok {
  984. merged[key] = append([]any(nil), masks...)
  985. }
  986. default:
  987. merged[key] = value
  988. }
  989. }
  990. }
  991. for key, value := range extra {
  992. switch key {
  993. case "tcp", "udp":
  994. baseMasks, _ := merged[key].([]any)
  995. extraMasks, _ := value.([]any)
  996. if len(extraMasks) > 0 {
  997. merged[key] = append(baseMasks, extraMasks...)
  998. }
  999. case "quicParams":
  1000. if _, exists := merged[key]; !exists {
  1001. merged[key] = value
  1002. }
  1003. default:
  1004. merged[key] = value
  1005. }
  1006. }
  1007. return merged
  1008. }
  1009. type Outbound struct {
  1010. Protocol string `json:"protocol"`
  1011. Tag string `json:"tag"`
  1012. StreamSettings json_util.RawMessage `json:"streamSettings"`
  1013. Mux json_util.RawMessage `json:"mux,omitempty"`
  1014. Settings map[string]any `json:"settings,omitempty"`
  1015. }
  1016. type ServerSetting struct {
  1017. Password string `json:"password"`
  1018. Level int `json:"level"`
  1019. Address string `json:"address"`
  1020. Port int `json:"port"`
  1021. Flow string `json:"flow,omitempty"`
  1022. Method string `json:"method,omitempty"`
  1023. }