json_service.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. outbound.Mux = muxWithoutTCP(mux)
  727. }
  728. outbound.Settings = settings
  729. result, _ := json.MarshalIndent(outbound, "", " ")
  730. return result
  731. }
  732. // XTLS flows reject TCP mux.cool ("unexpected network TCP"); concurrency -1
  733. // turns only that off and keeps the XUDP keys (Xray reads them under enabled).
  734. func muxWithoutTCP(mux string) json_util.RawMessage {
  735. if mux == "" {
  736. return nil
  737. }
  738. var m map[string]any
  739. if err := json.Unmarshal([]byte(mux), &m); err != nil || m == nil {
  740. return nil
  741. }
  742. m["concurrency"] = -1
  743. out, err := json.Marshal(m)
  744. if err != nil {
  745. return nil
  746. }
  747. return json_util.RawMessage(out)
  748. }
  749. func (s *SubJsonService) genServer(subReq *SubService, inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, mux string) json_util.RawMessage {
  750. outbound := Outbound{}
  751. serverData := make([]ServerSetting, 1)
  752. serverData[0] = ServerSetting{
  753. Address: inbound.Listen,
  754. Port: inbound.Port,
  755. Level: 8,
  756. Password: client.Password,
  757. }
  758. if inbound.Protocol == model.Shadowsocks {
  759. inboundSettings := subReq.linkSettings(inbound)
  760. method, _ := inboundSettings["method"].(string)
  761. serverData[0].Method = method
  762. // server password in multi-user 2022 protocols
  763. if strings.HasPrefix(method, "2022") {
  764. if serverPassword, ok := inboundSettings["password"].(string); ok {
  765. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  766. }
  767. }
  768. }
  769. outbound.Protocol = string(inbound.Protocol)
  770. outbound.Tag = "proxy"
  771. if mux != "" {
  772. outbound.Mux = json_util.RawMessage(mux)
  773. }
  774. outbound.StreamSettings = streamSettings
  775. // Wrap the endpoint in a "servers" array (the standard Xray schema for
  776. // Shadowsocks/Trojan outbounds). The flat top-level form only parses on very
  777. // recent xray-core; older bundled cores (e.g. in v2rayN) reject it, so SS
  778. // links fail to connect. See genVnext/genVless for the VMess/VLESS shape.
  779. server := map[string]any{
  780. "address": serverData[0].Address,
  781. "port": serverData[0].Port,
  782. "password": serverData[0].Password,
  783. "level": 8,
  784. }
  785. if inbound.Protocol == model.Shadowsocks {
  786. server["method"] = serverData[0].Method
  787. }
  788. outbound.Settings = map[string]any{
  789. "servers": []any{server},
  790. }
  791. result, _ := json.MarshalIndent(outbound, "", " ")
  792. return result
  793. }
  794. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client, mux string) json_util.RawMessage {
  795. outbound := Outbound{
  796. Protocol: string(inbound.Protocol),
  797. Tag: "proxy",
  798. }
  799. if mux != "" {
  800. outbound.Mux = json_util.RawMessage(mux)
  801. }
  802. var settings, stream map[string]any
  803. _ = json.Unmarshal([]byte(inbound.Settings), &settings)
  804. version, _ := settings["version"].(float64)
  805. outbound.Settings = map[string]any{
  806. "version": int(version),
  807. "address": inbound.Listen,
  808. "port": inbound.Port,
  809. }
  810. _ = json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  811. hyStream, _ := stream["hysteriaSettings"].(map[string]any)
  812. outHyStream := map[string]any{
  813. "version": int(version),
  814. "auth": client.Auth,
  815. }
  816. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  817. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  818. }
  819. if masquerade, ok := hyStream["masquerade"].(map[string]any); ok {
  820. outHyStream["masquerade"] = masquerade
  821. }
  822. newStream["hysteriaSettings"] = outHyStream
  823. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  824. newStream["finalmask"] = mergeFinalMask(newStream["finalmask"], finalmask)
  825. }
  826. newStream["network"] = "hysteria"
  827. newStream["security"] = "tls"
  828. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  829. result, _ := json.MarshalIndent(outbound, "", " ")
  830. return result
  831. }
  832. // genWireguard builds an Xray wireguard outbound for a native WireGuard inbound,
  833. // mirroring genWireguardLink: the peer public key is derived from the inbound
  834. // secretKey, the client owns the private key / tunnel address / pre-shared key,
  835. // and the peer routes the full tunnel. Returns nil when the client has no key.
  836. func (s *SubJsonService) genWireguard(inbound *model.Inbound, client model.Client) json_util.RawMessage {
  837. if client.PrivateKey == "" {
  838. return nil
  839. }
  840. var inboundSettings map[string]any
  841. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  842. secretKey, _ := inboundSettings["secretKey"].(string)
  843. peer := map[string]any{
  844. "endpoint": joinHostPort(inbound.Listen, inbound.Port),
  845. "allowedIPs": []string{"0.0.0.0/0", "::/0"},
  846. }
  847. if secretKey != "" {
  848. if pub, err := wgutil.PublicKeyFromPrivate(secretKey); err == nil {
  849. peer["publicKey"] = pub
  850. }
  851. }
  852. if client.PreSharedKey != "" {
  853. peer["preSharedKey"] = client.PreSharedKey
  854. }
  855. if client.KeepAlive > 0 {
  856. peer["keepAlive"] = client.KeepAlive
  857. }
  858. settings := map[string]any{
  859. "secretKey": client.PrivateKey,
  860. "peers": []any{peer},
  861. }
  862. if len(client.AllowedIPs) > 0 {
  863. settings["address"] = client.AllowedIPs
  864. }
  865. if mtu, ok := inboundSettings["mtu"].(float64); ok && mtu > 0 {
  866. settings["mtu"] = int(mtu)
  867. }
  868. outbound := map[string]any{
  869. "protocol": string(inbound.Protocol),
  870. "tag": "proxy",
  871. "settings": settings,
  872. }
  873. result, _ := json.MarshalIndent(outbound, "", " ")
  874. return result
  875. }
  876. func mergeFinalMask(base any, extra map[string]any) map[string]any {
  877. merged := map[string]any{}
  878. if baseMap, ok := base.(map[string]any); ok {
  879. for key, value := range baseMap {
  880. switch key {
  881. case "tcp", "udp":
  882. if masks, ok := value.([]any); ok {
  883. merged[key] = append([]any(nil), masks...)
  884. }
  885. default:
  886. merged[key] = value
  887. }
  888. }
  889. }
  890. for key, value := range extra {
  891. switch key {
  892. case "tcp", "udp":
  893. baseMasks, _ := merged[key].([]any)
  894. extraMasks, _ := value.([]any)
  895. if len(extraMasks) > 0 {
  896. merged[key] = append(baseMasks, extraMasks...)
  897. }
  898. case "quicParams":
  899. if _, exists := merged[key]; !exists {
  900. merged[key] = value
  901. }
  902. default:
  903. merged[key] = value
  904. }
  905. }
  906. return merged
  907. }
  908. type Outbound struct {
  909. Protocol string `json:"protocol"`
  910. Tag string `json:"tag"`
  911. StreamSettings json_util.RawMessage `json:"streamSettings"`
  912. Mux json_util.RawMessage `json:"mux,omitempty"`
  913. Settings map[string]any `json:"settings,omitempty"`
  914. }
  915. type ServerSetting struct {
  916. Password string `json:"password"`
  917. Level int `json:"level"`
  918. Address string `json:"address"`
  919. Port int `json:"port"`
  920. Flow string `json:"flow,omitempty"`
  921. Method string `json:"method,omitempty"`
  922. }