subJsonService.go 11 KB

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