subJsonService.go 10 KB

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