json_service.go 34 KB

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