1
0

json_service.go 32 KB

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