json_service.go 33 KB

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