subJsonService.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. package sub
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "fmt"
  6. "maps"
  7. "strings"
  8. "github.com/mhsanaei/3x-ui/v2/database/model"
  9. "github.com/mhsanaei/3x-ui/v2/logger"
  10. "github.com/mhsanaei/3x-ui/v2/util/json_util"
  11. "github.com/mhsanaei/3x-ui/v2/util/random"
  12. "github.com/mhsanaei/3x-ui/v2/web/service"
  13. "github.com/mhsanaei/3x-ui/v2/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. fragment string
  22. noises string
  23. mux string
  24. inboundService service.InboundService
  25. SubService *SubService
  26. }
  27. // NewSubJsonService creates a new JSON subscription service with the given configuration.
  28. func NewSubJsonService(fragment string, noises string, mux string, rules string, subService *SubService) *SubJsonService {
  29. var configJson map[string]any
  30. var defaultOutbounds []json_util.RawMessage
  31. json.Unmarshal([]byte(defaultJson), &configJson)
  32. if outboundSlices, ok := configJson["outbounds"].([]any); ok {
  33. for _, defaultOutbound := range outboundSlices {
  34. jsonBytes, _ := json.Marshal(defaultOutbound)
  35. defaultOutbounds = append(defaultOutbounds, jsonBytes)
  36. }
  37. }
  38. if rules != "" {
  39. var newRules []any
  40. routing, _ := configJson["routing"].(map[string]any)
  41. defaultRules, _ := routing["rules"].([]any)
  42. json.Unmarshal([]byte(rules), &newRules)
  43. defaultRules = append(newRules, defaultRules...)
  44. routing["rules"] = defaultRules
  45. configJson["routing"] = routing
  46. }
  47. if fragment != "" {
  48. defaultOutbounds = append(defaultOutbounds, json_util.RawMessage(fragment))
  49. }
  50. if noises != "" {
  51. defaultOutbounds = append(defaultOutbounds, json_util.RawMessage(noises))
  52. }
  53. return &SubJsonService{
  54. configJson: configJson,
  55. defaultOutbounds: defaultOutbounds,
  56. fragment: fragment,
  57. noises: noises,
  58. mux: mux,
  59. SubService: subService,
  60. }
  61. }
  62. // GetJson generates a JSON subscription configuration for the given subscription ID and host.
  63. func (s *SubJsonService) GetJson(subId string, host string) (string, string, error) {
  64. inbounds, err := s.SubService.getInboundsBySubId(subId)
  65. if err != nil || len(inbounds) == 0 {
  66. return "", "", err
  67. }
  68. var header string
  69. var traffic xray.ClientTraffic
  70. var clientTraffics []xray.ClientTraffic
  71. var configArray []json_util.RawMessage
  72. // Prepare Inbounds
  73. for _, inbound := range inbounds {
  74. clients, err := s.inboundService.GetClients(inbound)
  75. if err != nil {
  76. logger.Error("SubJsonService - GetClients: Unable to get clients from inbound")
  77. }
  78. if clients == nil {
  79. continue
  80. }
  81. if len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  82. listen, port, streamSettings, err := s.SubService.getFallbackMaster(inbound.Listen, inbound.StreamSettings)
  83. if err == nil {
  84. inbound.Listen = listen
  85. inbound.Port = port
  86. inbound.StreamSettings = streamSettings
  87. }
  88. }
  89. for _, client := range clients {
  90. if client.Enable && client.SubID == subId {
  91. clientTraffics = append(clientTraffics, s.SubService.getClientTraffics(inbound.ClientStats, client.Email))
  92. newConfigs := s.getConfig(inbound, client, host)
  93. configArray = append(configArray, newConfigs...)
  94. }
  95. }
  96. }
  97. if len(configArray) == 0 {
  98. return "", "", nil
  99. }
  100. // Prepare statistics
  101. for index, clientTraffic := range clientTraffics {
  102. if index == 0 {
  103. traffic.Up = clientTraffic.Up
  104. traffic.Down = clientTraffic.Down
  105. traffic.Total = clientTraffic.Total
  106. if clientTraffic.ExpiryTime > 0 {
  107. traffic.ExpiryTime = clientTraffic.ExpiryTime
  108. }
  109. } else {
  110. traffic.Up += clientTraffic.Up
  111. traffic.Down += clientTraffic.Down
  112. if traffic.Total == 0 || clientTraffic.Total == 0 {
  113. traffic.Total = 0
  114. } else {
  115. traffic.Total += clientTraffic.Total
  116. }
  117. if clientTraffic.ExpiryTime != traffic.ExpiryTime {
  118. traffic.ExpiryTime = 0
  119. }
  120. }
  121. }
  122. // Combile outbounds
  123. var finalJson []byte
  124. if len(configArray) == 1 {
  125. finalJson, _ = json.MarshalIndent(configArray[0], "", " ")
  126. } else {
  127. finalJson, _ = json.MarshalIndent(configArray, "", " ")
  128. }
  129. header = fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  130. return string(finalJson), header, nil
  131. }
  132. func (s *SubJsonService) getConfig(inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage {
  133. var newJsonArray []json_util.RawMessage
  134. stream := s.streamData(inbound.StreamSettings)
  135. externalProxies, ok := stream["externalProxy"].([]any)
  136. if !ok || len(externalProxies) == 0 {
  137. externalProxies = []any{
  138. map[string]any{
  139. "forceTls": "same",
  140. "dest": host,
  141. "port": float64(inbound.Port),
  142. "remark": "",
  143. },
  144. }
  145. }
  146. delete(stream, "externalProxy")
  147. for _, ep := range externalProxies {
  148. extPrxy := ep.(map[string]any)
  149. inbound.Listen = extPrxy["dest"].(string)
  150. inbound.Port = int(extPrxy["port"].(float64))
  151. newStream := stream
  152. switch extPrxy["forceTls"].(string) {
  153. case "tls":
  154. if newStream["security"] != "tls" {
  155. newStream["security"] = "tls"
  156. newStream["tlsSettings"] = map[string]any{}
  157. }
  158. case "none":
  159. if newStream["security"] != "none" {
  160. newStream["security"] = "none"
  161. delete(newStream, "tlsSettings")
  162. }
  163. }
  164. streamSettings, _ := json.MarshalIndent(newStream, "", " ")
  165. var newOutbounds []json_util.RawMessage
  166. switch inbound.Protocol {
  167. case "vmess":
  168. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client))
  169. case "vless":
  170. newOutbounds = append(newOutbounds, s.genVless(inbound, streamSettings, client))
  171. case "trojan", "shadowsocks":
  172. newOutbounds = append(newOutbounds, s.genServer(inbound, streamSettings, client))
  173. }
  174. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  175. newConfigJson := make(map[string]any)
  176. maps.Copy(newConfigJson, s.configJson)
  177. newConfigJson["outbounds"] = newOutbounds
  178. newConfigJson["remarks"] = s.SubService.genRemark(inbound, client.Email, extPrxy["remark"].(string))
  179. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  180. newJsonArray = append(newJsonArray, newConfig)
  181. }
  182. return newJsonArray
  183. }
  184. func (s *SubJsonService) streamData(stream string) map[string]any {
  185. var streamSettings map[string]any
  186. json.Unmarshal([]byte(stream), &streamSettings)
  187. security, _ := streamSettings["security"].(string)
  188. switch security {
  189. case "tls":
  190. streamSettings["tlsSettings"] = s.tlsData(streamSettings["tlsSettings"].(map[string]any))
  191. case "reality":
  192. streamSettings["realitySettings"] = s.realityData(streamSettings["realitySettings"].(map[string]any))
  193. }
  194. delete(streamSettings, "sockopt")
  195. if s.fragment != "" {
  196. streamSettings["sockopt"] = json_util.RawMessage(`{"dialerProxy": "fragment", "tcpKeepAliveIdle": 100, "tcpMptcp": true, "penetrate": true}`)
  197. }
  198. // remove proxy protocol
  199. network, _ := streamSettings["network"].(string)
  200. switch network {
  201. case "tcp":
  202. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  203. case "ws":
  204. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  205. case "httpupgrade":
  206. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  207. }
  208. return streamSettings
  209. }
  210. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  211. netSettings, ok := setting.(map[string]any)
  212. if ok {
  213. delete(netSettings, "acceptProxyProtocol")
  214. }
  215. return netSettings
  216. }
  217. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  218. tlsData := make(map[string]any, 1)
  219. tlsClientSettings, _ := tData["settings"].(map[string]any)
  220. tlsData["serverName"] = tData["serverName"]
  221. tlsData["alpn"] = tData["alpn"]
  222. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  223. tlsData["fingerprint"] = fingerprint
  224. }
  225. return tlsData
  226. }
  227. func (s *SubJsonService) realityData(rData map[string]any) map[string]any {
  228. rltyData := make(map[string]any, 1)
  229. rltyClientSettings, _ := rData["settings"].(map[string]any)
  230. rltyData["show"] = false
  231. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  232. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  233. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  234. // Set random data
  235. rltyData["spiderX"] = "/" + random.Seq(15)
  236. shortIds, ok := rData["shortIds"].([]any)
  237. if ok && len(shortIds) > 0 {
  238. rltyData["shortId"] = shortIds[random.Num(len(shortIds))].(string)
  239. } else {
  240. rltyData["shortId"] = ""
  241. }
  242. serverNames, ok := rData["serverNames"].([]any)
  243. if ok && len(serverNames) > 0 {
  244. rltyData["serverName"] = serverNames[random.Num(len(serverNames))].(string)
  245. } else {
  246. rltyData["serverName"] = ""
  247. }
  248. return rltyData
  249. }
  250. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  251. outbound := Outbound{}
  252. usersData := make([]UserVnext, 1)
  253. usersData[0].ID = client.ID
  254. usersData[0].Email = client.Email
  255. usersData[0].Security = client.Security
  256. vnextData := make([]VnextSetting, 1)
  257. vnextData[0] = VnextSetting{
  258. Address: inbound.Listen,
  259. Port: inbound.Port,
  260. Users: usersData,
  261. }
  262. outbound.Protocol = string(inbound.Protocol)
  263. outbound.Tag = "proxy"
  264. if s.mux != "" {
  265. outbound.Mux = json_util.RawMessage(s.mux)
  266. }
  267. outbound.StreamSettings = streamSettings
  268. outbound.Settings = map[string]any{
  269. "vnext": vnextData,
  270. }
  271. result, _ := json.MarshalIndent(outbound, "", " ")
  272. return result
  273. }
  274. func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  275. outbound := Outbound{}
  276. outbound.Protocol = string(inbound.Protocol)
  277. outbound.Tag = "proxy"
  278. if s.mux != "" {
  279. outbound.Mux = json_util.RawMessage(s.mux)
  280. }
  281. outbound.StreamSettings = streamSettings
  282. settings := make(map[string]any)
  283. settings["address"] = inbound.Listen
  284. settings["port"] = inbound.Port
  285. settings["id"] = client.ID
  286. if client.Flow != "" {
  287. settings["flow"] = client.Flow
  288. }
  289. // Add encryption for VLESS outbound from inbound settings
  290. var inboundSettings map[string]any
  291. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  292. if encryption, ok := inboundSettings["encryption"].(string); ok {
  293. settings["encryption"] = encryption
  294. }
  295. outbound.Settings = settings
  296. result, _ := json.MarshalIndent(outbound, "", " ")
  297. return result
  298. }
  299. func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  300. outbound := Outbound{}
  301. serverData := make([]ServerSetting, 1)
  302. serverData[0] = ServerSetting{
  303. Address: inbound.Listen,
  304. Port: inbound.Port,
  305. Level: 8,
  306. Password: client.Password,
  307. }
  308. if inbound.Protocol == model.Shadowsocks {
  309. var inboundSettings map[string]any
  310. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  311. method, _ := inboundSettings["method"].(string)
  312. serverData[0].Method = method
  313. // server password in multi-user 2022 protocols
  314. if strings.HasPrefix(method, "2022") {
  315. if serverPassword, ok := inboundSettings["password"].(string); ok {
  316. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  317. }
  318. }
  319. }
  320. outbound.Protocol = string(inbound.Protocol)
  321. outbound.Tag = "proxy"
  322. if s.mux != "" {
  323. outbound.Mux = json_util.RawMessage(s.mux)
  324. }
  325. outbound.StreamSettings = streamSettings
  326. outbound.Settings = map[string]any{
  327. "servers": serverData,
  328. }
  329. result, _ := json.MarshalIndent(outbound, "", " ")
  330. return result
  331. }
  332. type Outbound struct {
  333. Protocol string `json:"protocol"`
  334. Tag string `json:"tag"`
  335. StreamSettings json_util.RawMessage `json:"streamSettings"`
  336. Mux json_util.RawMessage `json:"mux,omitempty"`
  337. Settings map[string]any `json:"settings,omitempty"`
  338. }
  339. type VnextSetting struct {
  340. Address string `json:"address"`
  341. Port int `json:"port"`
  342. Users []UserVnext `json:"users"`
  343. }
  344. type UserVnext struct {
  345. ID string `json:"id"`
  346. Email string `json:"email,omitempty"`
  347. Security string `json:"security,omitempty"`
  348. }
  349. type ServerSetting struct {
  350. Password string `json:"password"`
  351. Level int `json:"level"`
  352. Address string `json:"address"`
  353. Port int `json:"port"`
  354. Flow string `json:"flow,omitempty"`
  355. Method string `json:"method,omitempty"`
  356. }