json_service.go 37 KB

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