subJsonService.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. package sub
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "fmt"
  6. "maps"
  7. "strings"
  8. "github.com/mhsanaei/3x-ui/v3/database/model"
  9. "github.com/mhsanaei/3x-ui/v3/logger"
  10. "github.com/mhsanaei/3x-ui/v3/util/json_util"
  11. "github.com/mhsanaei/3x-ui/v3/util/random"
  12. "github.com/mhsanaei/3x-ui/v3/web/service"
  13. "github.com/mhsanaei/3x-ui/v3/xray"
  14. )
  15. //go:embed default.json
  16. var defaultJson string
  17. // SubJsonService handles JSON subscription configuration generation and management.
  18. type SubJsonService struct {
  19. configJson map[string]any
  20. defaultOutbounds []json_util.RawMessage
  21. fragmentOrNoises bool
  22. mux string
  23. inboundService service.InboundService
  24. SubService *SubService
  25. }
  26. // NewSubJsonService creates a new JSON subscription service with the given configuration.
  27. func NewSubJsonService(fragment string, noises string, mux string, rules string, subService *SubService) *SubJsonService {
  28. var configJson map[string]any
  29. var defaultOutbounds []json_util.RawMessage
  30. json.Unmarshal([]byte(defaultJson), &configJson)
  31. if outboundSlices, ok := configJson["outbounds"].([]any); ok {
  32. for _, defaultOutbound := range outboundSlices {
  33. jsonBytes, _ := json.Marshal(defaultOutbound)
  34. defaultOutbounds = append(defaultOutbounds, jsonBytes)
  35. }
  36. }
  37. fragmentOrNoises := false
  38. if fragment != "" || noises != "" {
  39. fragmentOrNoises = true
  40. defaultOutboundsSettings := map[string]any{
  41. "domainStrategy": "UseIP",
  42. "redirect": "",
  43. }
  44. if fragment != "" {
  45. defaultOutboundsSettings["fragment"] = json_util.RawMessage(fragment)
  46. }
  47. if noises != "" {
  48. defaultOutboundsSettings["noises"] = json_util.RawMessage(noises)
  49. }
  50. defaultDirectOutbound := map[string]any{
  51. "protocol": "freedom",
  52. "settings": defaultOutboundsSettings,
  53. "tag": "direct_out",
  54. }
  55. jsonBytes, _ := json.MarshalIndent(defaultDirectOutbound, "", " ")
  56. defaultOutbounds = append(defaultOutbounds, jsonBytes)
  57. }
  58. if rules != "" {
  59. var newRules []any
  60. routing, _ := configJson["routing"].(map[string]any)
  61. defaultRules, _ := routing["rules"].([]any)
  62. json.Unmarshal([]byte(rules), &newRules)
  63. defaultRules = append(newRules, defaultRules...)
  64. routing["rules"] = defaultRules
  65. configJson["routing"] = routing
  66. }
  67. return &SubJsonService{
  68. configJson: configJson,
  69. defaultOutbounds: defaultOutbounds,
  70. fragmentOrNoises: fragmentOrNoises,
  71. mux: mux,
  72. SubService: subService,
  73. }
  74. }
  75. // GetJson generates a JSON subscription configuration for the given subscription ID and host.
  76. func (s *SubJsonService) GetJson(subId string, host string) (string, string, error) {
  77. // Set per-request state on the shared SubService so any
  78. // resolveInboundAddress call inside picks node-aware host values.
  79. s.SubService.PrepareForRequest(host)
  80. inbounds, err := s.SubService.getInboundsBySubId(subId)
  81. if err != nil || len(inbounds) == 0 {
  82. return "", "", err
  83. }
  84. var header string
  85. var traffic xray.ClientTraffic
  86. var clientTraffics []xray.ClientTraffic
  87. var configArray []json_util.RawMessage
  88. seenEmails := make(map[string]struct{})
  89. // Prepare Inbounds
  90. for _, inbound := range inbounds {
  91. clients, err := s.inboundService.GetClients(inbound)
  92. if err != nil {
  93. logger.Error("SubJsonService - GetClients: Unable to get clients from inbound")
  94. }
  95. if clients == nil {
  96. continue
  97. }
  98. s.SubService.projectThroughFallbackMaster(inbound)
  99. for _, client := range clients {
  100. if client.SubID == subId {
  101. _, clientTraffics = s.SubService.appendUniqueTraffic(seenEmails, clientTraffics, inbound.ClientStats, client.Email)
  102. configArray = append(configArray, s.getConfig(inbound, client, host)...)
  103. }
  104. }
  105. }
  106. if len(configArray) == 0 {
  107. return "", "", nil
  108. }
  109. // Prepare statistics
  110. for index, clientTraffic := range clientTraffics {
  111. if index == 0 {
  112. traffic.Up = clientTraffic.Up
  113. traffic.Down = clientTraffic.Down
  114. traffic.Total = clientTraffic.Total
  115. if clientTraffic.ExpiryTime > 0 {
  116. traffic.ExpiryTime = clientTraffic.ExpiryTime
  117. }
  118. } else {
  119. traffic.Up += clientTraffic.Up
  120. traffic.Down += clientTraffic.Down
  121. if traffic.Total == 0 || clientTraffic.Total == 0 {
  122. traffic.Total = 0
  123. } else {
  124. traffic.Total += clientTraffic.Total
  125. }
  126. if clientTraffic.ExpiryTime != traffic.ExpiryTime {
  127. traffic.ExpiryTime = 0
  128. }
  129. }
  130. }
  131. // Combile outbounds
  132. var finalJson []byte
  133. if len(configArray) == 1 {
  134. finalJson, _ = json.MarshalIndent(configArray[0], "", " ")
  135. } else {
  136. finalJson, _ = json.MarshalIndent(configArray, "", " ")
  137. }
  138. header = fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  139. return string(finalJson), header, nil
  140. }
  141. func (s *SubJsonService) getConfig(inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage {
  142. var newJsonArray []json_util.RawMessage
  143. stream := s.streamData(inbound.StreamSettings)
  144. // When externalProxy is empty the JSON config falls back to a
  145. // synthetic one whose `dest` is the host the client connects to.
  146. // For node-managed inbounds we want the node's address — request
  147. // host won't reach the right xray. resolveInboundAddress already
  148. // implements the node→listen→request-host fallback chain.
  149. defaultDest := s.SubService.resolveInboundAddress(inbound)
  150. if defaultDest == "" {
  151. defaultDest = host
  152. }
  153. externalProxies, ok := stream["externalProxy"].([]any)
  154. hasExternalProxy := ok && len(externalProxies) > 0
  155. if !hasExternalProxy {
  156. externalProxies = []any{
  157. map[string]any{
  158. "forceTls": "same",
  159. "dest": defaultDest,
  160. "port": float64(inbound.Port),
  161. "remark": "",
  162. },
  163. }
  164. }
  165. delete(stream, "externalProxy")
  166. for _, ep := range externalProxies {
  167. extPrxy := ep.(map[string]any)
  168. inbound.Listen = extPrxy["dest"].(string)
  169. inbound.Port = int(extPrxy["port"].(float64))
  170. newStream := cloneStreamForExternalProxy(stream)
  171. switch extPrxy["forceTls"].(string) {
  172. case "tls":
  173. if newStream["security"] != "tls" {
  174. newStream["security"] = "tls"
  175. newStream["tlsSettings"] = map[string]any{}
  176. }
  177. case "none":
  178. if newStream["security"] != "none" {
  179. newStream["security"] = "none"
  180. delete(newStream, "tlsSettings")
  181. }
  182. }
  183. security, _ := newStream["security"].(string)
  184. if hasExternalProxy {
  185. applyExternalProxyTLSToStream(extPrxy, newStream, security)
  186. }
  187. streamSettings, _ := json.MarshalIndent(newStream, "", " ")
  188. var newOutbounds []json_util.RawMessage
  189. switch inbound.Protocol {
  190. case "vmess":
  191. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client))
  192. case "vless":
  193. newOutbounds = append(newOutbounds, s.genVless(inbound, streamSettings, client))
  194. case "trojan", "shadowsocks":
  195. newOutbounds = append(newOutbounds, s.genServer(inbound, streamSettings, client))
  196. case "hysteria", "hysteria2":
  197. newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client))
  198. }
  199. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  200. newConfigJson := make(map[string]any)
  201. maps.Copy(newConfigJson, s.configJson)
  202. newConfigJson["outbounds"] = newOutbounds
  203. newConfigJson["remarks"] = s.SubService.genRemark(inbound, client.Email, extPrxy["remark"].(string))
  204. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  205. newJsonArray = append(newJsonArray, newConfig)
  206. }
  207. return newJsonArray
  208. }
  209. func (s *SubJsonService) streamData(stream string) map[string]any {
  210. var streamSettings map[string]any
  211. json.Unmarshal([]byte(stream), &streamSettings)
  212. security, _ := streamSettings["security"].(string)
  213. switch security {
  214. case "tls":
  215. streamSettings["tlsSettings"] = s.tlsData(streamSettings["tlsSettings"].(map[string]any))
  216. case "reality":
  217. streamSettings["realitySettings"] = s.realityData(streamSettings["realitySettings"].(map[string]any))
  218. }
  219. delete(streamSettings, "sockopt")
  220. if s.fragmentOrNoises {
  221. streamSettings["sockopt"] = json_util.RawMessage(`{"dialerProxy": "direct_out", "tcpKeepAliveIdle": 100}`)
  222. }
  223. // remove proxy protocol
  224. network, _ := streamSettings["network"].(string)
  225. switch network {
  226. case "tcp":
  227. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  228. case "ws":
  229. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  230. case "httpupgrade":
  231. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  232. case "xhttp":
  233. streamSettings["xhttpSettings"] = s.removeAcceptProxy(streamSettings["xhttpSettings"])
  234. if xhttp, ok := streamSettings["xhttpSettings"].(map[string]any); ok {
  235. delete(xhttp, "noSSEHeader")
  236. delete(xhttp, "scMaxBufferedPosts")
  237. delete(xhttp, "scStreamUpServerSecs")
  238. delete(xhttp, "serverMaxHeaderBytes")
  239. }
  240. }
  241. return streamSettings
  242. }
  243. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  244. netSettings, ok := setting.(map[string]any)
  245. if ok {
  246. delete(netSettings, "acceptProxyProtocol")
  247. }
  248. return netSettings
  249. }
  250. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  251. tlsData := make(map[string]any, 1)
  252. tlsClientSettings, _ := tData["settings"].(map[string]any)
  253. tlsData["serverName"] = tData["serverName"]
  254. tlsData["alpn"] = tData["alpn"]
  255. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  256. tlsData["fingerprint"] = fingerprint
  257. }
  258. return tlsData
  259. }
  260. func (s *SubJsonService) realityData(rData map[string]any) map[string]any {
  261. rltyData := make(map[string]any, 1)
  262. rltyClientSettings, _ := rData["settings"].(map[string]any)
  263. rltyData["show"] = false
  264. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  265. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  266. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  267. // Set random data
  268. rltyData["spiderX"] = "/" + random.Seq(15)
  269. shortIds, ok := rData["shortIds"].([]any)
  270. if ok && len(shortIds) > 0 {
  271. rltyData["shortId"] = shortIds[random.Num(len(shortIds))].(string)
  272. } else {
  273. rltyData["shortId"] = ""
  274. }
  275. serverNames, ok := rData["serverNames"].([]any)
  276. if ok && len(serverNames) > 0 {
  277. rltyData["serverName"] = serverNames[random.Num(len(serverNames))].(string)
  278. } else {
  279. rltyData["serverName"] = ""
  280. }
  281. return rltyData
  282. }
  283. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  284. outbound := Outbound{}
  285. usersData := make([]UserVnext, 1)
  286. usersData[0].ID = client.ID
  287. usersData[0].Email = client.Email
  288. usersData[0].Security = client.Security
  289. vnextData := make([]VnextSetting, 1)
  290. vnextData[0] = VnextSetting{
  291. Address: inbound.Listen,
  292. Port: inbound.Port,
  293. Users: usersData,
  294. }
  295. outbound.Protocol = string(inbound.Protocol)
  296. outbound.Tag = "proxy"
  297. if s.mux != "" {
  298. outbound.Mux = json_util.RawMessage(s.mux)
  299. }
  300. outbound.StreamSettings = streamSettings
  301. outbound.Settings = map[string]any{
  302. "vnext": vnextData,
  303. }
  304. result, _ := json.MarshalIndent(outbound, "", " ")
  305. return result
  306. }
  307. func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  308. outbound := Outbound{}
  309. outbound.Protocol = string(inbound.Protocol)
  310. outbound.Tag = "proxy"
  311. if s.mux != "" {
  312. outbound.Mux = json_util.RawMessage(s.mux)
  313. }
  314. outbound.StreamSettings = streamSettings
  315. // Add encryption for VLESS outbound from inbound settings
  316. var inboundSettings map[string]any
  317. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  318. encryption, _ := inboundSettings["encryption"].(string)
  319. user := map[string]any{
  320. "id": client.ID,
  321. "level": 8,
  322. "encryption": encryption,
  323. }
  324. if client.Flow != "" {
  325. user["flow"] = client.Flow
  326. }
  327. vnext := map[string]any{
  328. "address": inbound.Listen,
  329. "port": inbound.Port,
  330. "users": []any{user},
  331. }
  332. outbound.Settings = map[string]any{
  333. "vnext": []any{vnext},
  334. }
  335. result, _ := json.MarshalIndent(outbound, "", " ")
  336. return result
  337. }
  338. func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  339. outbound := Outbound{}
  340. serverData := make([]ServerSetting, 1)
  341. serverData[0] = ServerSetting{
  342. Address: inbound.Listen,
  343. Port: inbound.Port,
  344. Level: 8,
  345. Password: client.Password,
  346. }
  347. if inbound.Protocol == model.Shadowsocks {
  348. var inboundSettings map[string]any
  349. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  350. method, _ := inboundSettings["method"].(string)
  351. serverData[0].Method = method
  352. // server password in multi-user 2022 protocols
  353. if strings.HasPrefix(method, "2022") {
  354. if serverPassword, ok := inboundSettings["password"].(string); ok {
  355. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  356. }
  357. }
  358. }
  359. outbound.Protocol = string(inbound.Protocol)
  360. outbound.Tag = "proxy"
  361. if s.mux != "" {
  362. outbound.Mux = json_util.RawMessage(s.mux)
  363. }
  364. outbound.StreamSettings = streamSettings
  365. outbound.Settings = map[string]any{
  366. "servers": serverData,
  367. }
  368. result, _ := json.MarshalIndent(outbound, "", " ")
  369. return result
  370. }
  371. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client) json_util.RawMessage {
  372. outbound := Outbound{}
  373. outbound.Protocol = string(inbound.Protocol)
  374. outbound.Tag = "proxy"
  375. if s.mux != "" {
  376. outbound.Mux = json_util.RawMessage(s.mux)
  377. }
  378. var settings, stream map[string]any
  379. json.Unmarshal([]byte(inbound.Settings), &settings)
  380. version, _ := settings["version"].(float64)
  381. outbound.Settings = map[string]any{
  382. "version": int(version),
  383. "address": inbound.Listen,
  384. "port": inbound.Port,
  385. }
  386. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  387. hyStream := stream["hysteriaSettings"].(map[string]any)
  388. outHyStream := map[string]any{
  389. "version": int(version),
  390. "auth": client.Auth,
  391. }
  392. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  393. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  394. }
  395. if masquerade, ok := hyStream["masquerade"].(map[string]any); ok {
  396. outHyStream["masquerade"] = masquerade
  397. }
  398. newStream["hysteriaSettings"] = outHyStream
  399. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  400. newStream["finalmask"] = finalmask
  401. }
  402. newStream["network"] = "hysteria"
  403. newStream["security"] = "tls"
  404. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  405. result, _ := json.MarshalIndent(outbound, "", " ")
  406. return result
  407. }
  408. type Outbound struct {
  409. Protocol string `json:"protocol"`
  410. Tag string `json:"tag"`
  411. StreamSettings json_util.RawMessage `json:"streamSettings"`
  412. Mux json_util.RawMessage `json:"mux,omitempty"`
  413. Settings map[string]any `json:"settings,omitempty"`
  414. }
  415. type VnextSetting struct {
  416. Address string `json:"address"`
  417. Port int `json:"port"`
  418. Users []UserVnext `json:"users"`
  419. }
  420. type UserVnext struct {
  421. ID string `json:"id"`
  422. Email string `json:"email,omitempty"`
  423. Security string `json:"security,omitempty"`
  424. }
  425. type ServerSetting struct {
  426. Password string `json:"password"`
  427. Level int `json:"level"`
  428. Address string `json:"address"`
  429. Port int `json:"port"`
  430. Flow string `json:"flow,omitempty"`
  431. Method string `json:"method,omitempty"`
  432. }