json_service.go 31 KB

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