json_service.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  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. // buildBalancerConfig assembles the balancer profile: members retagged under a
  326. // per-balancer prefix, a routing.balancers entry, and (for leastPing/leastLoad) an observatory.
  327. func (s *SubJsonService) buildBalancerConfig(balancer *model.SubBalancer, entries []subConfigEntry, entryProxies [][]map[string]any) json_util.RawMessage {
  328. prefix := fmt.Sprintf("bal-%d-", balancer.Id)
  329. usedTags := make(map[string]bool)
  330. var proxies []json_util.RawMessage
  331. var firstTag string
  332. // entryProxies is the pre-extracted proxy outbounds per entry; kind!=0 rows
  333. // have none. Clone before retagging so the cached map stays reusable.
  334. for i, entry := range entries {
  335. if entry.kind != 0 || !slices.Contains(balancer.InboundIds, entry.id) {
  336. continue
  337. }
  338. for _, outbound := range entryProxies[i] {
  339. protocol, _ := outbound["protocol"].(string)
  340. base := prefix + balancerMemberSuffix(protocol)
  341. tag := base
  342. for suffix := 2; usedTags[tag]; suffix++ {
  343. tag = fmt.Sprintf("%s-%d", base, suffix)
  344. }
  345. usedTags[tag] = true
  346. member := maps.Clone(outbound)
  347. member["tag"] = tag
  348. if raw, err := json.MarshalIndent(member, "", " "); err == nil {
  349. if firstTag == "" {
  350. firstTag = tag
  351. }
  352. proxies = append(proxies, raw)
  353. }
  354. }
  355. }
  356. if len(proxies) == 0 {
  357. return nil
  358. }
  359. outbounds := append([]json_util.RawMessage{}, proxies...)
  360. outbounds = append(outbounds, s.defaultOutbounds...)
  361. // The routing subtree in s.configJson is shared by every emitted document;
  362. // clone it (and each rule map) before pointing rules at the balancer.
  363. baseRouting, _ := s.configJson["routing"].(map[string]any)
  364. routing := make(map[string]any, len(baseRouting)+1)
  365. maps.Copy(routing, baseRouting)
  366. baseRules, _ := baseRouting["rules"].([]any)
  367. rules := make([]any, 0, len(baseRules)+1)
  368. for _, rule := range baseRules {
  369. ruleMap, ok := rule.(map[string]any)
  370. if !ok {
  371. rules = append(rules, rule)
  372. continue
  373. }
  374. ruleMap = maps.Clone(ruleMap)
  375. if ruleMap["outboundTag"] == "proxy" {
  376. delete(ruleMap, "outboundTag")
  377. ruleMap["balancerTag"] = subBalancerTag
  378. }
  379. rules = append(rules, ruleMap)
  380. }
  381. routing["rules"] = rules
  382. isObservatory := balancer.Strategy == "leastPing" || balancer.Strategy == "leastLoad"
  383. balancerEntry := map[string]any{
  384. "tag": subBalancerTag,
  385. "selector": []string{prefix},
  386. "strategy": map[string]any{"type": balancer.Strategy},
  387. }
  388. if isObservatory && firstTag != "" {
  389. // With all probes failing, route to the first member instead of
  390. // failing dispatch.
  391. balancerEntry["fallbackTag"] = firstTag
  392. }
  393. routing["balancers"] = []any{balancerEntry}
  394. newConfigJson := make(map[string]any, len(s.configJson)+2)
  395. maps.Copy(newConfigJson, s.configJson)
  396. newConfigJson["outbounds"] = outbounds
  397. newConfigJson["remarks"] = balancer.Remark
  398. newConfigJson["routing"] = routing
  399. // leastPing/leastLoad require a burst observatory (Xray refuses to start
  400. // them without one); fallbackTag above covers the probe-outage case.
  401. if isObservatory {
  402. newConfigJson["burstObservatory"] = s.balancerObservatory(prefix)
  403. }
  404. config, _ := json.MarshalIndent(newConfigJson, "", " ")
  405. return config
  406. }
  407. func (s *SubJsonService) getConfig(subReq *SubService, inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage {
  408. var newJsonArray []json_util.RawMessage
  409. stream := s.streamData(inbound.StreamSettings, subKey(client))
  410. // When externalProxy is empty the JSON config falls back to a
  411. // synthetic one whose `dest` is the host the client connects to.
  412. // For node-managed inbounds we want the node's address — request
  413. // host won't reach the right xray. resolveInboundAddress already
  414. // implements the node→subscriber-host fallback chain.
  415. defaultDest := subReq.resolveInboundAddress(inbound)
  416. if defaultDest == "" {
  417. defaultDest = host
  418. }
  419. // Per-inbound xmux takes precedence over the global subJsonMux.
  420. // When xmux is present inside xhttpSettings, XHTTP multiplexing
  421. // is handled by xmux — don't also set the legacy outbound.Mux.
  422. mux := s.mux
  423. if xhttp, ok := stream["xhttpSettings"].(map[string]any); ok {
  424. if _, hasXmux := xhttp["xmux"]; hasXmux {
  425. mux = ""
  426. }
  427. }
  428. externalProxies, ok := stream["externalProxy"].([]any)
  429. hasExternalProxy := ok && len(externalProxies) > 0
  430. if !hasExternalProxy {
  431. externalProxies = []any{
  432. map[string]any{
  433. "forceTls": "same",
  434. "dest": defaultDest,
  435. "port": float64(inbound.Port),
  436. "remark": "",
  437. },
  438. }
  439. }
  440. delete(stream, "externalProxy")
  441. network, _ := stream["network"].(string)
  442. for _, ep := range externalProxies {
  443. extPrxy, ok := ep.(map[string]any)
  444. if !ok {
  445. continue
  446. }
  447. // Expand the host's {{VAR}} remark template for this client (no-op for
  448. // the synthetic/legacy entry) before it's used as the config remark.
  449. subReq.renderHostRemark(inbound, client, extPrxy, network)
  450. inbound.Listen, _ = extPrxy["dest"].(string)
  451. if port, ok := extPrxy["port"].(float64); ok {
  452. inbound.Port = int(port)
  453. }
  454. newStream := cloneStreamForExternalProxy(stream)
  455. forceTls, _ := extPrxy["forceTls"].(string)
  456. switch forceTls {
  457. case "tls":
  458. if newStream["security"] != "tls" {
  459. newStream["security"] = "tls"
  460. newStream["tlsSettings"] = map[string]any{}
  461. }
  462. case "none":
  463. if newStream["security"] != "none" {
  464. newStream["security"] = "none"
  465. delete(newStream, "tlsSettings")
  466. }
  467. }
  468. security, _ := newStream["security"].(string)
  469. if hasExternalProxy {
  470. applyExternalProxyTLSToStream(extPrxy, newStream, security)
  471. }
  472. applyHostStreamOverrides(extPrxy, newStream)
  473. streamSettings, _ := json.MarshalIndent(newStream, "", " ")
  474. hostMux := hostMuxOverride(extPrxy)
  475. var newOutbounds []json_util.RawMessage
  476. switch inbound.Protocol {
  477. case "vmess":
  478. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client, jsonMux(mux, hostMux)))
  479. case "vless":
  480. vc := client
  481. vc.ID = applyVlessRoute(client.ID, hostVlessRoute(extPrxy))
  482. // Same gate the raw link and the Clash proxy apply: a flow left
  483. // over from a transport Vision supported produces an outbound
  484. // xray refuses to start.
  485. newNetwork, _ := newStream["network"].(string)
  486. if vc.Flow != "" && !vlessFlowAllowed(newNetwork, security, subReq.linkSettings(inbound)) {
  487. vc.Flow = ""
  488. }
  489. newOutbounds = append(newOutbounds, s.genVless(subReq, inbound, streamSettings, vc, jsonMux(mux, hostMux)))
  490. case "trojan", "shadowsocks":
  491. newOutbounds = append(newOutbounds, s.genServer(subReq, inbound, streamSettings, client, jsonMux(mux, hostMux)))
  492. case "hysteria":
  493. newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client, jsonMux(mux, hostMux)))
  494. case "wireguard":
  495. wgOutbound := s.genWireguard(inbound, client)
  496. if wgOutbound == nil {
  497. continue
  498. }
  499. newOutbounds = append(newOutbounds, wgOutbound)
  500. }
  501. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  502. newConfigJson := make(map[string]any)
  503. maps.Copy(newConfigJson, s.configJson)
  504. transport, _ := newStream["network"].(string)
  505. newConfigJson["outbounds"] = newOutbounds
  506. newConfigJson["remarks"] = subReq.endpointRemark(inbound, client.Email, extPrxy, transport)
  507. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  508. newJsonArray = append(newJsonArray, newConfig)
  509. }
  510. return newJsonArray
  511. }
  512. func (s *SubJsonService) streamData(stream string, clientKey string) map[string]any {
  513. var streamSettings map[string]any
  514. if err := json.Unmarshal([]byte(stream), &streamSettings); err != nil || streamSettings == nil {
  515. streamSettings = map[string]any{}
  516. }
  517. security, _ := streamSettings["security"].(string)
  518. switch security {
  519. case "tls":
  520. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  521. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  522. } else {
  523. delete(streamSettings, "tlsSettings")
  524. }
  525. case "reality":
  526. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  527. streamSettings["realitySettings"] = s.realityData(realitySettings, clientKey)
  528. } else {
  529. delete(streamSettings, "realitySettings")
  530. }
  531. }
  532. delete(streamSettings, "sockopt")
  533. if s.finalMask != "" {
  534. s.applyGlobalFinalMask(streamSettings)
  535. }
  536. // remove proxy protocol
  537. network, _ := streamSettings["network"].(string)
  538. switch network {
  539. case "tcp":
  540. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  541. case "ws":
  542. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  543. case "httpupgrade":
  544. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  545. case "xhttp":
  546. streamSettings["xhttpSettings"] = s.removeAcceptProxy(streamSettings["xhttpSettings"])
  547. if xhttp, ok := streamSettings["xhttpSettings"].(map[string]any); ok {
  548. delete(xhttp, "noSSEHeader")
  549. delete(xhttp, "scMaxBufferedPosts")
  550. delete(xhttp, "scStreamUpServerSecs")
  551. delete(xhttp, "serverMaxHeaderBytes")
  552. // Values matching xray-core's own defaults stay off the wire:
  553. // old panels seeded them into every stored config and the
  554. // literal scMinPostsIntervalMs=30 is a DPI fingerprint (#5141).
  555. if v, _ := xhttp["scMaxEachPostBytes"].(string); v == "" || v == "1000000" {
  556. delete(xhttp, "scMaxEachPostBytes")
  557. }
  558. if v, _ := xhttp["scMinPostsIntervalMs"].(string); v == "" || v == "30" {
  559. delete(xhttp, "scMinPostsIntervalMs")
  560. }
  561. }
  562. }
  563. return streamSettings
  564. }
  565. func (s *SubJsonService) applyGlobalFinalMask(streamSettings map[string]any) {
  566. var fm map[string]any
  567. if err := json.Unmarshal([]byte(s.finalMask), &fm); err != nil || len(fm) == 0 {
  568. return
  569. }
  570. merged := mergeFinalMask(streamSettings["finalmask"], fm)
  571. if len(merged) > 0 {
  572. streamSettings["finalmask"] = merged
  573. }
  574. }
  575. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  576. netSettings, ok := setting.(map[string]any)
  577. if ok {
  578. delete(netSettings, "acceptProxyProtocol")
  579. }
  580. return netSettings
  581. }
  582. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  583. tlsData := make(map[string]any, 1)
  584. tlsClientSettings, _ := tData["settings"].(map[string]any)
  585. tlsData["serverName"] = tData["serverName"]
  586. tlsData["alpn"] = tData["alpn"]
  587. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  588. tlsData["fingerprint"] = fingerprint
  589. }
  590. if ech, ok := tlsClientSettings["echConfigList"].(string); ok && ech != "" {
  591. tlsData["echConfigList"] = ech
  592. }
  593. if vcn, ok := verifyPeerCertByNameValue(tlsClientSettings); ok {
  594. tlsData["verifyPeerCertByName"] = vcn
  595. }
  596. // xray-core now parses pinnedPeerCertSha256 as a comma-separated string, not
  597. // an array; emit the joined form so v2ray clients can import the config (#5401).
  598. if pins, ok := pinnedSha256List(tlsClientSettings); ok {
  599. tlsData["pinnedPeerCertSha256"] = strings.Join(pins, ",")
  600. }
  601. return tlsData
  602. }
  603. func (s *SubJsonService) realityData(rData map[string]any, clientKey string) map[string]any {
  604. rltyData := make(map[string]any, 1)
  605. rltyClientSettings, _ := rData["settings"].(map[string]any)
  606. rltyData["show"] = false
  607. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  608. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  609. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  610. seed, _ := rltyClientSettings["spiderX"].(string)
  611. rltyData["spiderX"] = deriveSpiderX(seed, clientKey)
  612. shortIds, ok := rData["shortIds"].([]any)
  613. if ok && len(shortIds) > 0 {
  614. rltyData["shortId"], _ = shortIds[random.Num(len(shortIds))].(string)
  615. } else {
  616. rltyData["shortId"] = ""
  617. }
  618. serverNames, ok := rData["serverNames"].([]any)
  619. if ok && len(serverNames) > 0 {
  620. rltyData["serverName"], _ = serverNames[random.Num(len(serverNames))].(string)
  621. } else {
  622. rltyData["serverName"] = ""
  623. }
  624. return rltyData
  625. }
  626. // jsonMux picks the per-host mux override when present, else the global mux.
  627. func jsonMux(global, override string) string {
  628. if override != "" {
  629. return override
  630. }
  631. return global
  632. }
  633. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  634. outbound := Outbound{
  635. Protocol: string(inbound.Protocol),
  636. Tag: "proxy"}
  637. if mux != "" {
  638. outbound.Mux = json_util.RawMessage(mux)
  639. }
  640. outbound.StreamSettings = streamSettings
  641. security := normalizeVmessSecurity(client.Security)
  642. outbound.Settings = map[string]any{
  643. "address": inbound.Listen,
  644. "port": inbound.Port,
  645. "id": client.ID,
  646. "security": security,
  647. "level": 8,
  648. }
  649. result, _ := json.MarshalIndent(outbound, "", " ")
  650. return result
  651. }
  652. func (s *SubJsonService) genVless(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  653. outbound := Outbound{
  654. Protocol: string(inbound.Protocol),
  655. Tag: "proxy",
  656. }
  657. if mux != "" {
  658. outbound.Mux = json_util.RawMessage(mux)
  659. }
  660. outbound.StreamSettings = streamSettings
  661. // Add encryption for VLESS outbound from inbound settings
  662. inboundSettings := subReq.linkSettings(inbound)
  663. encryption, _ := inboundSettings["encryption"].(string)
  664. settings := map[string]any{
  665. "address": inbound.Listen,
  666. "port": inbound.Port,
  667. "id": client.ID,
  668. "encryption": encryption,
  669. "level": 8,
  670. }
  671. if client.Flow != "" && !inbound.DisableFlow {
  672. settings["flow"] = client.Flow
  673. }
  674. outbound.Settings = settings
  675. result, _ := json.MarshalIndent(outbound, "", " ")
  676. return result
  677. }
  678. func (s *SubJsonService) genServer(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  679. outbound := Outbound{}
  680. serverData := make([]ServerSetting, 1)
  681. serverData[0] = ServerSetting{
  682. Address: inbound.Listen,
  683. Port: inbound.Port,
  684. Level: 8,
  685. Password: client.Password,
  686. }
  687. if inbound.Protocol == model.Shadowsocks {
  688. inboundSettings := subReq.linkSettings(inbound)
  689. method, _ := inboundSettings["method"].(string)
  690. serverData[0].Method = method
  691. // server password in multi-user 2022 protocols
  692. if strings.HasPrefix(method, "2022") {
  693. if serverPassword, ok := inboundSettings["password"].(string); ok {
  694. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  695. }
  696. }
  697. }
  698. outbound.Protocol = string(inbound.Protocol)
  699. outbound.Tag = "proxy"
  700. if mux != "" {
  701. outbound.Mux = json_util.RawMessage(mux)
  702. }
  703. outbound.StreamSettings = streamSettings
  704. // Wrap the endpoint in a "servers" array (the standard Xray schema for
  705. // Shadowsocks/Trojan outbounds). The flat top-level form only parses on very
  706. // recent xray-core; older bundled cores (e.g. in v2rayN) reject it, so SS
  707. // links fail to connect. See genVnext/genVless for the VMess/VLESS shape.
  708. server := map[string]any{
  709. "address": serverData[0].Address,
  710. "port": serverData[0].Port,
  711. "password": serverData[0].Password,
  712. "level": 8,
  713. }
  714. if inbound.Protocol == model.Shadowsocks {
  715. server["method"] = serverData[0].Method
  716. }
  717. outbound.Settings = map[string]any{
  718. "servers": []any{server},
  719. }
  720. result, _ := json.MarshalIndent(outbound, "", " ")
  721. return result
  722. }
  723. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client, mux string) json_util.RawMessage {
  724. outbound := Outbound{
  725. Protocol: string(inbound.Protocol),
  726. Tag: "proxy"}
  727. if mux != "" {
  728. outbound.Mux = json_util.RawMessage(mux)
  729. }
  730. var settings, stream map[string]any
  731. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  732. version, _ := settings["version"].(float64)
  733. outbound.Settings = map[string]any{
  734. "version": int(version),
  735. "address": inbound.Listen,
  736. "port": inbound.Port,
  737. }
  738. _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  739. hyStream, _ := stream["hysteriaSettings"].(map[string]any)
  740. outHyStream := map[string]any{
  741. "version": int(version),
  742. "auth": client.Auth,
  743. }
  744. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  745. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  746. }
  747. if masquerade, ok := hyStream["masquerade"].(map[string]any); ok {
  748. outHyStream["masquerade"] = masquerade
  749. }
  750. newStream["hysteriaSettings"] = outHyStream
  751. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  752. newStream["finalmask"] = mergeFinalMask(newStream["finalmask"], finalmask)
  753. }
  754. newStream["network"] = "hysteria"
  755. newStream["security"] = "tls"
  756. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  757. result, _ := json.MarshalIndent(outbound, "", " ")
  758. return result
  759. }
  760. // genWireguard builds an Xray wireguard outbound for a native WireGuard inbound,
  761. // mirroring genWireguardLink: the peer public key is derived from the inbound
  762. // secretKey, the client owns the private key / tunnel address / pre-shared key,
  763. // and the peer routes the full tunnel. Returns nil when the client has no key.
  764. func (s *SubJsonService) genWireguard(inbound *model.Inbound, client model.Client) json_util.RawMessage {
  765. if client.PrivateKey == "" {
  766. return nil
  767. }
  768. var inboundSettings map[string]any
  769. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  770. secretKey, _ := inboundSettings["secretKey"].(string)
  771. peer := map[string]any{
  772. "endpoint": joinHostPort(inbound.Listen, inbound.Port),
  773. "allowedIPs": []string{"0.0.0.0/0", "::/0"},
  774. }
  775. if secretKey != "" {
  776. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  777. peer["publicKey"] = pub
  778. }
  779. }
  780. if client.PreSharedKey != "" {
  781. peer["preSharedKey"] = client.PreSharedKey
  782. }
  783. if client.KeepAlive > 0 {
  784. peer["keepAlive"] = client.KeepAlive
  785. }
  786. settings := map[string]any{
  787. "secretKey": client.PrivateKey,
  788. "peers": []any{peer},
  789. }
  790. if len(client.AllowedIPs) > 0 {
  791. settings["address"] = client.AllowedIPs
  792. }
  793. if mtu, ok := inboundSettings["mtu"].(float64); ok && mtu > 0 {
  794. settings["mtu"] = int(mtu)
  795. }
  796. outbound := map[string]any{
  797. "protocol": string(inbound.Protocol),
  798. "tag": "proxy",
  799. "settings": settings,
  800. }
  801. result, _ := json.MarshalIndent(outbound, "", " ")
  802. return result
  803. }
  804. func mergeFinalMask(base any, extra map[string]any) map[string]any {
  805. merged := map[string]any{}
  806. if baseMap, ok := base.(map[string]any); ok {
  807. for key, value := range baseMap {
  808. switch key {
  809. case "tcp", "udp":
  810. if masks, ok := value.([]any); ok {
  811. merged[key] = append([]any(nil), masks...)
  812. }
  813. default:
  814. merged[key] = value
  815. }
  816. }
  817. }
  818. for key, value := range extra {
  819. switch key {
  820. case "tcp", "udp":
  821. baseMasks, _ := merged[key].([]any)
  822. extraMasks, _ := value.([]any)
  823. if len(extraMasks) > 0 {
  824. merged[key] = append(baseMasks, extraMasks...)
  825. }
  826. case "quicParams":
  827. if _, exists := merged[key]; !exists {
  828. merged[key] = value
  829. }
  830. default:
  831. merged[key] = value
  832. }
  833. }
  834. return merged
  835. }
  836. type Outbound struct {
  837. Protocol string `json:"protocol"`
  838. Tag string `json:"tag"`
  839. StreamSettings json_util.RawMessage `json:"streamSettings"`
  840. Mux json_util.RawMessage `json:"mux,omitempty"`
  841. Settings map[string]any `json:"settings,omitempty"`
  842. }
  843. type ServerSetting struct {
  844. Password string `json:"password"`
  845. Level int `json:"level"`
  846. Address string `json:"address"`
  847. Port int `json:"port"`
  848. Flow string `json:"flow,omitempty"`
  849. Method string `json:"method,omitempty"`
  850. }