subJsonService.go 11 KB

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