subJsonService.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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. 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]interface{}{
  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]interface{}{
  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. inbounds, err := s.SubService.getInboundsBySubId(subId)
  78. if err != nil || len(inbounds) == 0 {
  79. return "", "", err
  80. }
  81. var header string
  82. var traffic xray.ClientTraffic
  83. var clientTraffics []xray.ClientTraffic
  84. var configArray []json_util.RawMessage
  85. // Prepare Inbounds
  86. for _, inbound := range inbounds {
  87. clients, err := s.inboundService.GetClients(inbound)
  88. if err != nil {
  89. logger.Error("SubJsonService - GetClients: Unable to get clients from inbound")
  90. }
  91. if clients == nil {
  92. continue
  93. }
  94. if len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  95. listen, port, streamSettings, err := s.SubService.getFallbackMaster(inbound.Listen, inbound.StreamSettings)
  96. if err == nil {
  97. inbound.Listen = listen
  98. inbound.Port = port
  99. inbound.StreamSettings = streamSettings
  100. }
  101. }
  102. for _, client := range clients {
  103. if client.Enable && client.SubID == subId {
  104. clientTraffics = append(clientTraffics, s.SubService.getClientTraffics(inbound.ClientStats, client.Email))
  105. newConfigs := s.getConfig(inbound, client, host)
  106. configArray = append(configArray, newConfigs...)
  107. }
  108. }
  109. }
  110. if len(configArray) == 0 {
  111. return "", "", nil
  112. }
  113. // Prepare statistics
  114. for index, clientTraffic := range clientTraffics {
  115. if index == 0 {
  116. traffic.Up = clientTraffic.Up
  117. traffic.Down = clientTraffic.Down
  118. traffic.Total = clientTraffic.Total
  119. if clientTraffic.ExpiryTime > 0 {
  120. traffic.ExpiryTime = clientTraffic.ExpiryTime
  121. }
  122. } else {
  123. traffic.Up += clientTraffic.Up
  124. traffic.Down += clientTraffic.Down
  125. if traffic.Total == 0 || clientTraffic.Total == 0 {
  126. traffic.Total = 0
  127. } else {
  128. traffic.Total += clientTraffic.Total
  129. }
  130. if clientTraffic.ExpiryTime != traffic.ExpiryTime {
  131. traffic.ExpiryTime = 0
  132. }
  133. }
  134. }
  135. // Combile outbounds
  136. var finalJson []byte
  137. if len(configArray) == 1 {
  138. finalJson, _ = json.MarshalIndent(configArray[0], "", " ")
  139. } else {
  140. finalJson, _ = json.MarshalIndent(configArray, "", " ")
  141. }
  142. header = fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  143. return string(finalJson), header, nil
  144. }
  145. func (s *SubJsonService) getConfig(inbound *model.Inbound, client model.Client, host string) []json_util.RawMessage {
  146. var newJsonArray []json_util.RawMessage
  147. stream := s.streamData(inbound.StreamSettings)
  148. externalProxies, ok := stream["externalProxy"].([]any)
  149. if !ok || len(externalProxies) == 0 {
  150. externalProxies = []any{
  151. map[string]any{
  152. "forceTls": "same",
  153. "dest": host,
  154. "port": float64(inbound.Port),
  155. "remark": "",
  156. },
  157. }
  158. }
  159. delete(stream, "externalProxy")
  160. for _, ep := range externalProxies {
  161. extPrxy := ep.(map[string]any)
  162. inbound.Listen = extPrxy["dest"].(string)
  163. inbound.Port = int(extPrxy["port"].(float64))
  164. newStream := stream
  165. switch extPrxy["forceTls"].(string) {
  166. case "tls":
  167. if newStream["security"] != "tls" {
  168. newStream["security"] = "tls"
  169. newStream["tlsSettings"] = map[string]any{}
  170. }
  171. case "none":
  172. if newStream["security"] != "none" {
  173. newStream["security"] = "none"
  174. delete(newStream, "tlsSettings")
  175. }
  176. }
  177. streamSettings, _ := json.MarshalIndent(newStream, "", " ")
  178. var newOutbounds []json_util.RawMessage
  179. switch inbound.Protocol {
  180. case "vmess":
  181. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client))
  182. case "vless":
  183. newOutbounds = append(newOutbounds, s.genVless(inbound, streamSettings, client))
  184. case "trojan", "shadowsocks":
  185. newOutbounds = append(newOutbounds, s.genServer(inbound, streamSettings, client))
  186. case "hysteria", "hysteria2":
  187. newOutbounds = append(newOutbounds, s.genHy(inbound, newStream, client))
  188. }
  189. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  190. newConfigJson := make(map[string]any)
  191. maps.Copy(newConfigJson, s.configJson)
  192. newConfigJson["outbounds"] = newOutbounds
  193. newConfigJson["remarks"] = s.SubService.genRemark(inbound, client.Email, extPrxy["remark"].(string))
  194. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  195. newJsonArray = append(newJsonArray, newConfig)
  196. }
  197. return newJsonArray
  198. }
  199. func (s *SubJsonService) streamData(stream string) map[string]any {
  200. var streamSettings map[string]any
  201. json.Unmarshal([]byte(stream), &streamSettings)
  202. security, _ := streamSettings["security"].(string)
  203. switch security {
  204. case "tls":
  205. streamSettings["tlsSettings"] = s.tlsData(streamSettings["tlsSettings"].(map[string]any))
  206. case "reality":
  207. streamSettings["realitySettings"] = s.realityData(streamSettings["realitySettings"].(map[string]any))
  208. }
  209. delete(streamSettings, "sockopt")
  210. if s.fragmentOrNoises {
  211. streamSettings["sockopt"] = json_util.RawMessage(`{"dialerProxy": "direct_out", "tcpKeepAliveIdle": 100}`)
  212. }
  213. // remove proxy protocol
  214. network, _ := streamSettings["network"].(string)
  215. switch network {
  216. case "tcp":
  217. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  218. case "ws":
  219. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  220. case "httpupgrade":
  221. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  222. }
  223. return streamSettings
  224. }
  225. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  226. netSettings, ok := setting.(map[string]any)
  227. if ok {
  228. delete(netSettings, "acceptProxyProtocol")
  229. }
  230. return netSettings
  231. }
  232. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  233. tlsData := make(map[string]any, 1)
  234. tlsClientSettings, _ := tData["settings"].(map[string]any)
  235. tlsData["serverName"] = tData["serverName"]
  236. tlsData["alpn"] = tData["alpn"]
  237. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  238. tlsData["fingerprint"] = fingerprint
  239. }
  240. return tlsData
  241. }
  242. func (s *SubJsonService) realityData(rData map[string]any) map[string]any {
  243. rltyData := make(map[string]any, 1)
  244. rltyClientSettings, _ := rData["settings"].(map[string]any)
  245. rltyData["show"] = false
  246. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  247. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  248. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  249. // Set random data
  250. rltyData["spiderX"] = "/" + random.Seq(15)
  251. shortIds, ok := rData["shortIds"].([]any)
  252. if ok && len(shortIds) > 0 {
  253. rltyData["shortId"] = shortIds[random.Num(len(shortIds))].(string)
  254. } else {
  255. rltyData["shortId"] = ""
  256. }
  257. serverNames, ok := rData["serverNames"].([]any)
  258. if ok && len(serverNames) > 0 {
  259. rltyData["serverName"] = serverNames[random.Num(len(serverNames))].(string)
  260. } else {
  261. rltyData["serverName"] = ""
  262. }
  263. return rltyData
  264. }
  265. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  266. outbound := Outbound{}
  267. usersData := make([]UserVnext, 1)
  268. usersData[0].ID = client.ID
  269. usersData[0].Email = client.Email
  270. usersData[0].Security = client.Security
  271. vnextData := make([]VnextSetting, 1)
  272. vnextData[0] = VnextSetting{
  273. Address: inbound.Listen,
  274. Port: inbound.Port,
  275. Users: usersData,
  276. }
  277. outbound.Protocol = string(inbound.Protocol)
  278. outbound.Tag = "proxy"
  279. if s.mux != "" {
  280. outbound.Mux = json_util.RawMessage(s.mux)
  281. }
  282. outbound.StreamSettings = streamSettings
  283. outbound.Settings = map[string]any{
  284. "vnext": vnextData,
  285. }
  286. result, _ := json.MarshalIndent(outbound, "", " ")
  287. return result
  288. }
  289. func (s *SubJsonService) genVless(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  290. outbound := Outbound{}
  291. outbound.Protocol = string(inbound.Protocol)
  292. outbound.Tag = "proxy"
  293. if s.mux != "" {
  294. outbound.Mux = json_util.RawMessage(s.mux)
  295. }
  296. outbound.StreamSettings = streamSettings
  297. // Add encryption for VLESS outbound from inbound settings
  298. var inboundSettings map[string]any
  299. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  300. encryption, _ := inboundSettings["encryption"].(string)
  301. user := map[string]any{
  302. "id": client.ID,
  303. "level": 8,
  304. "encryption": encryption,
  305. }
  306. if client.Flow != "" {
  307. user["flow"] = client.Flow
  308. }
  309. vnext := map[string]any{
  310. "address": inbound.Listen,
  311. "port": inbound.Port,
  312. "users": []any{user},
  313. }
  314. outbound.Settings = map[string]any{
  315. "vnext": []any{vnext},
  316. }
  317. result, _ := json.MarshalIndent(outbound, "", " ")
  318. return result
  319. }
  320. func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  321. outbound := Outbound{}
  322. serverData := make([]ServerSetting, 1)
  323. serverData[0] = ServerSetting{
  324. Address: inbound.Listen,
  325. Port: inbound.Port,
  326. Level: 8,
  327. Password: client.Password,
  328. }
  329. if inbound.Protocol == model.Shadowsocks {
  330. var inboundSettings map[string]any
  331. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  332. method, _ := inboundSettings["method"].(string)
  333. serverData[0].Method = method
  334. // server password in multi-user 2022 protocols
  335. if strings.HasPrefix(method, "2022") {
  336. if serverPassword, ok := inboundSettings["password"].(string); ok {
  337. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  338. }
  339. }
  340. }
  341. outbound.Protocol = string(inbound.Protocol)
  342. outbound.Tag = "proxy"
  343. if s.mux != "" {
  344. outbound.Mux = json_util.RawMessage(s.mux)
  345. }
  346. outbound.StreamSettings = streamSettings
  347. outbound.Settings = map[string]any{
  348. "servers": serverData,
  349. }
  350. result, _ := json.MarshalIndent(outbound, "", " ")
  351. return result
  352. }
  353. func (s *SubJsonService) genHy(inbound *model.Inbound, newStream map[string]any, client model.Client) json_util.RawMessage {
  354. outbound := Outbound{}
  355. outbound.Protocol = string(inbound.Protocol)
  356. outbound.Tag = "proxy"
  357. if s.mux != "" {
  358. outbound.Mux = json_util.RawMessage(s.mux)
  359. }
  360. var settings, stream map[string]any
  361. json.Unmarshal([]byte(inbound.Settings), &settings)
  362. version, _ := settings["version"].(float64)
  363. outbound.Settings = map[string]any{
  364. "version": int(version),
  365. "address": inbound.Listen,
  366. "port": inbound.Port,
  367. }
  368. json.Unmarshal([]byte(inbound.StreamSettings), &stream)
  369. hyStream := stream["hysteriaSettings"].(map[string]any)
  370. outHyStream := map[string]any{
  371. "version": int(version),
  372. "auth": client.Auth,
  373. }
  374. if udpIdleTimeout, ok := hyStream["udpIdleTimeout"].(float64); ok {
  375. outHyStream["udpIdleTimeout"] = int(udpIdleTimeout)
  376. }
  377. newStream["hysteriaSettings"] = outHyStream
  378. if finalmask, ok := hyStream["finalmask"].(map[string]any); ok {
  379. newStream["finalmask"] = finalmask
  380. }
  381. newStream["network"] = "hysteria"
  382. newStream["security"] = "tls"
  383. outbound.StreamSettings, _ = json.MarshalIndent(newStream, "", " ")
  384. result, _ := json.MarshalIndent(outbound, "", " ")
  385. return result
  386. }
  387. type Outbound struct {
  388. Protocol string `json:"protocol"`
  389. Tag string `json:"tag"`
  390. StreamSettings json_util.RawMessage `json:"streamSettings"`
  391. Mux json_util.RawMessage `json:"mux,omitempty"`
  392. Settings map[string]any `json:"settings,omitempty"`
  393. }
  394. type VnextSetting struct {
  395. Address string `json:"address"`
  396. Port int `json:"port"`
  397. Users []UserVnext `json:"users"`
  398. }
  399. type UserVnext struct {
  400. ID string `json:"id"`
  401. Email string `json:"email,omitempty"`
  402. Security string `json:"security,omitempty"`
  403. }
  404. type ServerSetting struct {
  405. Password string `json:"password"`
  406. Level int `json:"level"`
  407. Address string `json:"address"`
  408. Port int `json:"port"`
  409. Flow string `json:"flow,omitempty"`
  410. Method string `json:"method,omitempty"`
  411. }