subJsonService.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. if !ok || len(externalProxies) == 0 {
  155. externalProxies = []any{
  156. map[string]any{
  157. "forceTls": "same",
  158. "dest": defaultDest,
  159. "port": float64(inbound.Port),
  160. "remark": "",
  161. },
  162. }
  163. }
  164. delete(stream, "externalProxy")
  165. for _, ep := range externalProxies {
  166. extPrxy := ep.(map[string]any)
  167. inbound.Listen = extPrxy["dest"].(string)
  168. inbound.Port = int(extPrxy["port"].(float64))
  169. newStream := stream
  170. switch extPrxy["forceTls"].(string) {
  171. case "tls":
  172. if newStream["security"] != "tls" {
  173. newStream["security"] = "tls"
  174. newStream["tlsSettings"] = map[string]any{}
  175. }
  176. case "none":
  177. if newStream["security"] != "none" {
  178. newStream["security"] = "none"
  179. delete(newStream, "tlsSettings")
  180. }
  181. }
  182. streamSettings, _ := json.MarshalIndent(newStream, "", " ")
  183. var newOutbounds []json_util.RawMessage
  184. switch inbound.Protocol {
  185. case "vmess":
  186. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client))
  187. case "vless":
  188. newOutbounds = append(newOutbounds, s.genVless(inbound, streamSettings, client))
  189. case "trojan", "shadowsocks":
  190. newOutbounds = append(newOutbounds, s.genServer(inbound, streamSettings, client))
  191. case "hysteria", "hysteria2":
  192. newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client))
  193. }
  194. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  195. newConfigJson := make(map[string]any)
  196. maps.Copy(newConfigJson, s.configJson)
  197. newConfigJson["outbounds"] = newOutbounds
  198. newConfigJson["remarks"] = s.SubService.genRemark(inbound, client.Email, extPrxy["remark"].(string))
  199. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  200. newJsonArray = append(newJsonArray, newConfig)
  201. }
  202. return newJsonArray
  203. }
  204. func (s *SubJsonService) streamData(stream string) map[string]any {
  205. var streamSettings map[string]any
  206. json.Unmarshal([]byte(stream), &streamSettings)
  207. security, _ := streamSettings["security"].(string)
  208. switch security {
  209. case "tls":
  210. streamSettings["tlsSettings"] = s.tlsData(streamSettings["tlsSettings"].(map[string]any))
  211. case "reality":
  212. streamSettings["realitySettings"] = s.realityData(streamSettings["realitySettings"].(map[string]any))
  213. }
  214. delete(streamSettings, "sockopt")
  215. if s.fragmentOrNoises {
  216. streamSettings["sockopt"] = json_util.RawMessage(`{"dialerProxy": "direct_out", "tcpKeepAliveIdle": 100}`)
  217. }
  218. // remove proxy protocol
  219. network, _ := streamSettings["network"].(string)
  220. switch network {
  221. case "tcp":
  222. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  223. case "ws":
  224. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  225. case "httpupgrade":
  226. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  227. case "xhttp":
  228. streamSettings["xhttpSettings"] = s.removeAcceptProxy(streamSettings["xhttpSettings"])
  229. if xhttp, ok := streamSettings["xhttpSettings"].(map[string]any); ok {
  230. delete(xhttp, "noSSEHeader")
  231. delete(xhttp, "scMaxBufferedPosts")
  232. delete(xhttp, "scStreamUpServerSecs")
  233. delete(xhttp, "serverMaxHeaderBytes")
  234. }
  235. }
  236. return streamSettings
  237. }
  238. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  239. netSettings, ok := setting.(map[string]any)
  240. if ok {
  241. delete(netSettings, "acceptProxyProtocol")
  242. }
  243. return netSettings
  244. }
  245. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  246. tlsData := make(map[string]any, 1)
  247. tlsClientSettings, _ := tData["settings"].(map[string]any)
  248. tlsData["serverName"] = tData["serverName"]
  249. tlsData["alpn"] = tData["alpn"]
  250. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  251. tlsData["fingerprint"] = fingerprint
  252. }
  253. return tlsData
  254. }
  255. func (s *SubJsonService) realityData(rData map[string]any) map[string]any {
  256. rltyData := make(map[string]any, 1)
  257. rltyClientSettings, _ := rData["settings"].(map[string]any)
  258. rltyData["show"] = false
  259. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  260. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  261. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  262. // Set random data
  263. rltyData["spiderX"] = "/" + random.Seq(15)
  264. shortIds, ok := rData["shortIds"].([]any)
  265. if ok && len(shortIds) > 0 {
  266. rltyData["shortId"] = shortIds[random.Num(len(shortIds))].(string)
  267. } else {
  268. rltyData["shortId"] = ""
  269. }
  270. serverNames, ok := rData["serverNames"].([]any)
  271. if ok && len(serverNames) > 0 {
  272. rltyData["serverName"] = serverNames[random.Num(len(serverNames))].(string)
  273. } else {
  274. rltyData["serverName"] = ""
  275. }
  276. return rltyData
  277. }
  278. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  279. outbound := Outbound{}
  280. usersData := make([]UserVnext, 1)
  281. usersData[0].ID = client.ID
  282. usersData[0].Email = client.Email
  283. usersData[0].Security = client.Security
  284. vnextData := make([]VnextSetting, 1)
  285. vnextData[0] = VnextSetting{
  286. Address: inbound.Listen,
  287. Port: inbound.Port,
  288. Users: usersData,
  289. }
  290. outbound.Protocol = string(inbound.Protocol)
  291. outbound.Tag = "proxy"
  292. if s.mux != "" {
  293. outbound.Mux = json_util.RawMessage(s.mux)
  294. }
  295. outbound.StreamSettings = streamSettings
  296. outbound.Settings = map[string]any{
  297. "vnext": vnextData,
  298. }
  299. result, _ := json.MarshalIndent(outbound, "", " ")
  300. return result
  301. }
  302. func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  303. outbound := Outbound{}
  304. outbound.Protocol = string(inbound.Protocol)
  305. outbound.Tag = "proxy"
  306. if s.mux != "" {
  307. outbound.Mux = json_util.RawMessage(s.mux)
  308. }
  309. outbound.StreamSettings = streamSettings
  310. // Add encryption for VLESS outbound from inbound settings
  311. var inboundSettings map[string]any
  312. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  313. encryption, _ := inboundSettings["encryption"].(string)
  314. user := map[string]any{
  315. "id": client.ID,
  316. "level": 8,
  317. "encryption": encryption,
  318. }
  319. if client.Flow != "" {
  320. user["flow"] = client.Flow
  321. }
  322. vnext := map[string]any{
  323. "address": inbound.Listen,
  324. "port": inbound.Port,
  325. "users": []any{user},
  326. }
  327. outbound.Settings = map[string]any{
  328. "vnext": []any{vnext},
  329. }
  330. result, _ := json.MarshalIndent(outbound, "", " ")
  331. return result
  332. }
  333. func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  334. outbound := Outbound{}
  335. serverData := make([]ServerSetting, 1)
  336. serverData[0] = ServerSetting{
  337. Address: inbound.Listen,
  338. Port: inbound.Port,
  339. Level: 8,
  340. Password: client.Password,
  341. }
  342. if inbound.Protocol == model.Shadowsocks {
  343. var inboundSettings map[string]any
  344. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  345. method, _ := inboundSettings["method"].(string)
  346. serverData[0].Method = method
  347. // server password in multi-user 2022 protocols
  348. if strings.HasPrefix(method, "2022") {
  349. if serverPassword, ok := inboundSettings["password"].(string); ok {
  350. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  351. }
  352. }
  353. }
  354. outbound.Protocol = string(inbound.Protocol)
  355. outbound.Tag = "proxy"
  356. if s.mux != "" {
  357. outbound.Mux = json_util.RawMessage(s.mux)
  358. }
  359. outbound.StreamSettings = streamSettings
  360. outbound.Settings = map[string]any{
  361. "servers": serverData,
  362. }
  363. result, _ := json.MarshalIndent(outbound, "", " ")
  364. return result
  365. }
  366. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client) json_util.RawMessage {
  367. outbound := Outbound{}
  368. outbound.Protocol = string(inbound.Protocol)
  369. outbound.Tag = "proxy"
  370. if s.mux != "" {
  371. outbound.Mux = json_util.RawMessage(s.mux)
  372. }
  373. var settings, stream map[string]any
  374. json.Unmarshal([]byte(inbound.Settings), &settings)
  375. version, _ := settings["version"].(float64)
  376. outbound.Settings = map[string]any{
  377. "version": int(version),
  378. "address": inbound.Listen,
  379. "port": inbound.Port,
  380. }
  381. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  382. hyStream := stream["hysteriaSettings"].(map[string]any)
  383. outHyStream := map[string]any{
  384. "version": int(version),
  385. "auth": client.Auth,
  386. }
  387. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  388. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  389. }
  390. if masquerade, ok := hyStream["masquerade"].(map[string]any); ok {
  391. outHyStream["masquerade"] = masquerade
  392. }
  393. newStream["hysteriaSettings"] = outHyStream
  394. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  395. newStream["finalmask"] = finalmask
  396. }
  397. newStream["network"] = "hysteria"
  398. newStream["security"] = "tls"
  399. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  400. result, _ := json.MarshalIndent(outbound, "", " ")
  401. return result
  402. }
  403. type Outbound struct {
  404. Protocol string `json:"protocol"`
  405. Tag string `json:"tag"`
  406. StreamSettings json_util.RawMessage `json:"streamSettings"`
  407. Mux json_util.RawMessage `json:"mux,omitempty"`
  408. Settings map[string]any `json:"settings,omitempty"`
  409. }
  410. type VnextSetting struct {
  411. Address string `json:"address"`
  412. Port int `json:"port"`
  413. Users []UserVnext `json:"users"`
  414. }
  415. type UserVnext struct {
  416. ID string `json:"id"`
  417. Email string `json:"email,omitempty"`
  418. Security string `json:"security,omitempty"`
  419. }
  420. type ServerSetting struct {
  421. Password string `json:"password"`
  422. Level int `json:"level"`
  423. Address string `json:"address"`
  424. Port int `json:"port"`
  425. Flow string `json:"flow,omitempty"`
  426. Method string `json:"method,omitempty"`
  427. }