json_service.go 35 KB

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