subJsonService.go 11 KB

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