1
0

json_service.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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. }
  550. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  551. newConfigJson := make(map[string]any)
  552. maps.Copy(newConfigJson, s.configJson)
  553. transport, _ := newStream["network"].(string)
  554. newConfigJson["outbounds"] = newOutbounds
  555. newConfigJson["remarks"] = subReq.endpointRemark(inbound, client.Email, extPrxy, transport)
  556. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  557. newJsonArray = append(newJsonArray, newConfig)
  558. }
  559. return newJsonArray
  560. }
  561. func (s *SubJsonService) streamData(stream string, clientKey string) map[string]any {
  562. var streamSettings map[string]any
  563. if err := json.Unmarshal([]byte(stream), &streamSettings); err != nil || streamSettings == nil {
  564. streamSettings = map[string]any{}
  565. }
  566. security, _ := streamSettings["security"].(string)
  567. switch security {
  568. case "tls":
  569. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  570. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  571. } else {
  572. delete(streamSettings, "tlsSettings")
  573. }
  574. case "reality":
  575. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  576. streamSettings["realitySettings"] = s.realityData(realitySettings, clientKey)
  577. } else {
  578. delete(streamSettings, "realitySettings")
  579. }
  580. }
  581. delete(streamSettings, "sockopt")
  582. if s.finalMask != "" {
  583. s.applyGlobalFinalMask(streamSettings)
  584. }
  585. // remove proxy protocol
  586. network, _ := streamSettings["network"].(string)
  587. switch network {
  588. case "tcp":
  589. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  590. case "ws":
  591. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  592. case "httpupgrade":
  593. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  594. case "xhttp":
  595. streamSettings["xhttpSettings"] = s.removeAcceptProxy(streamSettings["xhttpSettings"])
  596. if xhttp, ok := streamSettings["xhttpSettings"].(map[string]any); ok {
  597. delete(xhttp, "noSSEHeader")
  598. delete(xhttp, "scMaxBufferedPosts")
  599. delete(xhttp, "scStreamUpServerSecs")
  600. delete(xhttp, "serverMaxHeaderBytes")
  601. // Values matching xray-core's own defaults stay off the wire:
  602. // old panels seeded them into every stored config and the
  603. // literal scMinPostsIntervalMs=30 is a DPI fingerprint (#5141).
  604. if v, _ := xhttp["scMaxEachPostBytes"].(string); v == "" || v == "1000000" {
  605. delete(xhttp, "scMaxEachPostBytes")
  606. }
  607. if v, _ := xhttp["scMinPostsIntervalMs"].(string); v == "" || v == "30" {
  608. delete(xhttp, "scMinPostsIntervalMs")
  609. }
  610. }
  611. }
  612. return streamSettings
  613. }
  614. func (s *SubJsonService) applyGlobalFinalMask(streamSettings map[string]any) {
  615. var fm map[string]any
  616. if err := json.Unmarshal([]byte(s.finalMask), &fm); err != nil || len(fm) == 0 {
  617. return
  618. }
  619. merged := mergeFinalMask(streamSettings["finalmask"], fm)
  620. if len(merged) > 0 {
  621. streamSettings["finalmask"] = merged
  622. }
  623. }
  624. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  625. netSettings, ok := setting.(map[string]any)
  626. if ok {
  627. delete(netSettings, "acceptProxyProtocol")
  628. }
  629. return netSettings
  630. }
  631. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  632. tlsData := make(map[string]any, 1)
  633. tlsClientSettings, _ := tData["settings"].(map[string]any)
  634. tlsData["serverName"] = tData["serverName"]
  635. tlsData["alpn"] = tData["alpn"]
  636. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  637. tlsData["fingerprint"] = fingerprint
  638. }
  639. if cs, ok := tData["cipherSuites"].(string); ok && cs != "" {
  640. tlsData["cipherSuites"] = cs
  641. }
  642. if ech, ok := tlsClientSettings["echConfigList"].(string); ok && ech != "" {
  643. tlsData["echConfigList"] = ech
  644. }
  645. if vcn, ok := verifyPeerCertByNameValue(tlsClientSettings); ok {
  646. tlsData["verifyPeerCertByName"] = vcn
  647. }
  648. // xray-core now parses pinnedPeerCertSha256 as a comma-separated string, not
  649. // an array; emit the joined form so v2ray clients can import the config (#5401).
  650. if pins, ok := pinnedSha256List(tlsClientSettings); ok {
  651. tlsData["pinnedPeerCertSha256"] = strings.Join(pins, ",")
  652. }
  653. return tlsData
  654. }
  655. func (s *SubJsonService) realityData(rData map[string]any, clientKey string) map[string]any {
  656. rltyData := make(map[string]any, 1)
  657. rltyClientSettings, _ := rData["settings"].(map[string]any)
  658. rltyData["show"] = false
  659. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  660. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  661. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  662. seed, _ := rltyClientSettings["spiderX"].(string)
  663. rltyData["spiderX"] = deriveSpiderX(seed, clientKey)
  664. shortIds, ok := rData["shortIds"].([]any)
  665. if ok && len(shortIds) > 0 {
  666. rltyData["shortId"], _ = shortIds[random.Num(len(shortIds))].(string)
  667. } else {
  668. rltyData["shortId"] = ""
  669. }
  670. serverNames, ok := rData["serverNames"].([]any)
  671. if ok && len(serverNames) > 0 {
  672. rltyData["serverName"], _ = serverNames[random.Num(len(serverNames))].(string)
  673. } else {
  674. rltyData["serverName"] = ""
  675. }
  676. return rltyData
  677. }
  678. // jsonMux picks the per-host mux override when present, else the global mux.
  679. func jsonMux(global, override string) string {
  680. if override != "" {
  681. return override
  682. }
  683. return global
  684. }
  685. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  686. outbound := Outbound{
  687. Protocol: string(inbound.Protocol),
  688. Tag: "proxy",
  689. }
  690. if mux != "" {
  691. outbound.Mux = json_util.RawMessage(mux)
  692. }
  693. outbound.StreamSettings = streamSettings
  694. security := normalizeVmessSecurity(client.Security)
  695. outbound.Settings = map[string]any{
  696. "address": inbound.Listen,
  697. "port": inbound.Port,
  698. "id": client.ID,
  699. "security": security,
  700. "level": 8,
  701. }
  702. result, _ := json.MarshalIndent(outbound, "", " ")
  703. return result
  704. }
  705. func (s *SubJsonService) genVless(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  706. outbound := Outbound{
  707. Protocol: string(inbound.Protocol),
  708. Tag: "proxy",
  709. }
  710. if mux != "" {
  711. outbound.Mux = json_util.RawMessage(mux)
  712. }
  713. outbound.StreamSettings = streamSettings
  714. // Add encryption for VLESS outbound from inbound settings
  715. inboundSettings := subReq.linkSettings(inbound)
  716. encryption, _ := inboundSettings["encryption"].(string)
  717. settings := map[string]any{
  718. "address": inbound.Listen,
  719. "port": inbound.Port,
  720. "id": client.ID,
  721. "encryption": encryption,
  722. "level": 8,
  723. }
  724. if client.Flow != "" && !inbound.DisableFlow {
  725. settings["flow"] = client.Flow
  726. }
  727. outbound.Settings = settings
  728. result, _ := json.MarshalIndent(outbound, "", " ")
  729. return result
  730. }
  731. func (s *SubJsonService) genServer(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  732. outbound := Outbound{}
  733. serverData := make([]ServerSetting, 1)
  734. serverData[0] = ServerSetting{
  735. Address: inbound.Listen,
  736. Port: inbound.Port,
  737. Level: 8,
  738. Password: client.Password,
  739. }
  740. if inbound.Protocol == model.Shadowsocks {
  741. inboundSettings := subReq.linkSettings(inbound)
  742. method, _ := inboundSettings["method"].(string)
  743. serverData[0].Method = method
  744. // server password in multi-user 2022 protocols
  745. if strings.HasPrefix(method, "2022") {
  746. if serverPassword, ok := inboundSettings["password"].(string); ok {
  747. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  748. }
  749. }
  750. }
  751. outbound.Protocol = string(inbound.Protocol)
  752. outbound.Tag = "proxy"
  753. if mux != "" {
  754. outbound.Mux = json_util.RawMessage(mux)
  755. }
  756. outbound.StreamSettings = streamSettings
  757. // Wrap the endpoint in a "servers" array (the standard Xray schema for
  758. // Shadowsocks/Trojan outbounds). The flat top-level form only parses on very
  759. // recent xray-core; older bundled cores (e.g. in v2rayN) reject it, so SS
  760. // links fail to connect. See genVnext/genVless for the VMess/VLESS shape.
  761. server := map[string]any{
  762. "address": serverData[0].Address,
  763. "port": serverData[0].Port,
  764. "password": serverData[0].Password,
  765. "level": 8,
  766. }
  767. if inbound.Protocol == model.Shadowsocks {
  768. server["method"] = serverData[0].Method
  769. }
  770. outbound.Settings = map[string]any{
  771. "servers": []any{server},
  772. }
  773. result, _ := json.MarshalIndent(outbound, "", " ")
  774. return result
  775. }
  776. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client, mux string) json_util.RawMessage {
  777. outbound := Outbound{
  778. Protocol: string(inbound.Protocol),
  779. Tag: "proxy",
  780. }
  781. if mux != "" {
  782. outbound.Mux = json_util.RawMessage(mux)
  783. }
  784. var settings, stream map[string]any
  785. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  786. version, _ := settings["version"].(float64)
  787. outbound.Settings = map[string]any{
  788. "version": int(version),
  789. "address": inbound.Listen,
  790. "port": inbound.Port,
  791. }
  792. _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  793. hyStream, _ := stream["hysteriaSettings"].(map[string]any)
  794. outHyStream := map[string]any{
  795. "version": int(version),
  796. "auth": client.Auth,
  797. }
  798. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  799. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  800. }
  801. if masquerade, ok := hyStream["masquerade"].(map[string]any); ok {
  802. outHyStream["masquerade"] = masquerade
  803. }
  804. newStream["hysteriaSettings"] = outHyStream
  805. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  806. newStream["finalmask"] = mergeFinalMask(newStream["finalmask"], finalmask)
  807. }
  808. newStream["network"] = "hysteria"
  809. newStream["security"] = "tls"
  810. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  811. result, _ := json.MarshalIndent(outbound, "", " ")
  812. return result
  813. }
  814. // genWireguard builds an Xray wireguard outbound for a native WireGuard inbound,
  815. // mirroring genWireguardLink: the peer public key is derived from the inbound
  816. // secretKey, the client owns the private key / tunnel address / pre-shared key,
  817. // and the peer routes the full tunnel. Returns nil when the client has no key.
  818. func (s *SubJsonService) genWireguard(inbound *model.Inbound, client model.Client) json_util.RawMessage {
  819. if client.PrivateKey == "" {
  820. return nil
  821. }
  822. var inboundSettings map[string]any
  823. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  824. secretKey, _ := inboundSettings["secretKey"].(string)
  825. peer := map[string]any{
  826. "endpoint": joinHostPort(inbound.Listen, inbound.Port),
  827. "allowedIPs": []string{"0.0.0.0/0", "::/0"},
  828. }
  829. if secretKey != "" {
  830. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  831. peer["publicKey"] = pub
  832. }
  833. }
  834. if client.PreSharedKey != "" {
  835. peer["preSharedKey"] = client.PreSharedKey
  836. }
  837. if client.KeepAlive > 0 {
  838. peer["keepAlive"] = client.KeepAlive
  839. }
  840. settings := map[string]any{
  841. "secretKey": client.PrivateKey,
  842. "peers": []any{peer},
  843. }
  844. if len(client.AllowedIPs) > 0 {
  845. settings["address"] = client.AllowedIPs
  846. }
  847. if mtu, ok := inboundSettings["mtu"].(float64); ok && mtu > 0 {
  848. settings["mtu"] = int(mtu)
  849. }
  850. outbound := map[string]any{
  851. "protocol": string(inbound.Protocol),
  852. "tag": "proxy",
  853. "settings": settings,
  854. }
  855. result, _ := json.MarshalIndent(outbound, "", " ")
  856. return result
  857. }
  858. func mergeFinalMask(base any, extra map[string]any) map[string]any {
  859. merged := map[string]any{}
  860. if baseMap, ok := base.(map[string]any); ok {
  861. for key, value := range baseMap {
  862. switch key {
  863. case "tcp", "udp":
  864. if masks, ok := value.([]any); ok {
  865. merged[key] = append([]any(nil), masks...)
  866. }
  867. default:
  868. merged[key] = value
  869. }
  870. }
  871. }
  872. for key, value := range extra {
  873. switch key {
  874. case "tcp", "udp":
  875. baseMasks, _ := merged[key].([]any)
  876. extraMasks, _ := value.([]any)
  877. if len(extraMasks) > 0 {
  878. merged[key] = append(baseMasks, extraMasks...)
  879. }
  880. case "quicParams":
  881. if _, exists := merged[key]; !exists {
  882. merged[key] = value
  883. }
  884. default:
  885. merged[key] = value
  886. }
  887. }
  888. return merged
  889. }
  890. type Outbound struct {
  891. Protocol string `json:"protocol"`
  892. Tag string `json:"tag"`
  893. StreamSettings json_util.RawMessage `json:"streamSettings"`
  894. Mux json_util.RawMessage `json:"mux,omitempty"`
  895. Settings map[string]any `json:"settings,omitempty"`
  896. }
  897. type ServerSetting struct {
  898. Password string `json:"password"`
  899. Level int `json:"level"`
  900. Address string `json:"address"`
  901. Port int `json:"port"`
  902. Flow string `json:"flow,omitempty"`
  903. Method string `json:"method,omitempty"`
  904. }