1
0

subJsonService.go 10 KB

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