subJsonService.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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]any
  18. defaultOutbounds []json_util.RawMessage
  19. fragment string
  20. noises string
  21. mux string
  22. inboundService service.InboundService
  23. SubService *SubService
  24. }
  25. func NewSubJsonService(fragment string, noises string, mux string, rules string, subService *SubService) *SubJsonService {
  26. var configJson map[string]any
  27. var defaultOutbounds []json_util.RawMessage
  28. json.Unmarshal([]byte(defaultJson), &configJson)
  29. if outboundSlices, ok := configJson["outbounds"].([]any); ok {
  30. for _, defaultOutbound := range outboundSlices {
  31. jsonBytes, _ := json.Marshal(defaultOutbound)
  32. defaultOutbounds = append(defaultOutbounds, jsonBytes)
  33. }
  34. }
  35. if rules != "" {
  36. var newRules []any
  37. routing, _ := configJson["routing"].(map[string]any)
  38. defaultRules, _ := routing["rules"].([]any)
  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 noises != "" {
  48. defaultOutbounds = append(defaultOutbounds, json_util.RawMessage(noises))
  49. }
  50. return &SubJsonService{
  51. configJson: configJson,
  52. defaultOutbounds: defaultOutbounds,
  53. fragment: fragment,
  54. noises: noises,
  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"].([]any)
  132. if !ok || len(externalProxies) == 0 {
  133. externalProxies = []any{
  134. map[string]any{
  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]any)
  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]any{}
  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":
  164. newOutbounds = append(newOutbounds, s.genVnext(inbound, streamSettings, client, ""))
  165. case "vless":
  166. var vlessSettings model.VLESSSettings
  167. _ = json.Unmarshal([]byte(inbound.Settings), &vlessSettings)
  168. newOutbounds = append(newOutbounds,
  169. s.genVnext(inbound, streamSettings, client, vlessSettings.Encryption))
  170. case "trojan", "shadowsocks":
  171. newOutbounds = append(newOutbounds, s.genServer(inbound, streamSettings, client))
  172. }
  173. newOutbounds = append(newOutbounds, s.defaultOutbounds...)
  174. newConfigJson := make(map[string]any)
  175. for key, value := range s.configJson {
  176. newConfigJson[key] = value
  177. }
  178. newConfigJson["outbounds"] = newOutbounds
  179. newConfigJson["remarks"] = s.SubService.genRemark(inbound, client.Email, extPrxy["remark"].(string))
  180. newConfig, _ := json.MarshalIndent(newConfigJson, "", " ")
  181. newJsonArray = append(newJsonArray, newConfig)
  182. }
  183. return newJsonArray
  184. }
  185. func (s *SubJsonService) streamData(stream string) map[string]any {
  186. var streamSettings map[string]any
  187. json.Unmarshal([]byte(stream), &streamSettings)
  188. security, _ := streamSettings["security"].(string)
  189. switch security {
  190. case "tls":
  191. streamSettings["tlsSettings"] = s.tlsData(streamSettings["tlsSettings"].(map[string]any))
  192. case "reality":
  193. streamSettings["realitySettings"] = s.realityData(streamSettings["realitySettings"].(map[string]any))
  194. }
  195. delete(streamSettings, "sockopt")
  196. if s.fragment != "" {
  197. streamSettings["sockopt"] = json_util.RawMessage(`{"dialerProxy": "fragment", "tcpKeepAliveIdle": 100, "tcpMptcp": true, "penetrate": true}`)
  198. }
  199. // remove proxy protocol
  200. network, _ := streamSettings["network"].(string)
  201. switch network {
  202. case "tcp":
  203. streamSettings["tcpSettings"] = s.removeAcceptProxy(streamSettings["tcpSettings"])
  204. case "ws":
  205. streamSettings["wsSettings"] = s.removeAcceptProxy(streamSettings["wsSettings"])
  206. case "httpupgrade":
  207. streamSettings["httpupgradeSettings"] = s.removeAcceptProxy(streamSettings["httpupgradeSettings"])
  208. }
  209. return streamSettings
  210. }
  211. func (s *SubJsonService) removeAcceptProxy(setting any) map[string]any {
  212. netSettings, ok := setting.(map[string]any)
  213. if ok {
  214. delete(netSettings, "acceptProxyProtocol")
  215. }
  216. return netSettings
  217. }
  218. func (s *SubJsonService) tlsData(tData map[string]any) map[string]any {
  219. tlsData := make(map[string]any, 1)
  220. tlsClientSettings, _ := tData["settings"].(map[string]any)
  221. tlsData["serverName"] = tData["serverName"]
  222. tlsData["alpn"] = tData["alpn"]
  223. if allowInsecure, ok := tlsClientSettings["allowInsecure"].(bool); ok {
  224. tlsData["allowInsecure"] = allowInsecure
  225. }
  226. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  227. tlsData["fingerprint"] = fingerprint
  228. }
  229. return tlsData
  230. }
  231. func (s *SubJsonService) realityData(rData map[string]any) map[string]any {
  232. rltyData := make(map[string]any, 1)
  233. rltyClientSettings, _ := rData["settings"].(map[string]any)
  234. rltyData["show"] = false
  235. rltyData["publicKey"] = rltyClientSettings["publicKey"]
  236. rltyData["fingerprint"] = rltyClientSettings["fingerprint"]
  237. rltyData["mldsa65Verify"] = rltyClientSettings["mldsa65Verify"]
  238. // Set random data
  239. rltyData["spiderX"] = "/" + random.Seq(15)
  240. shortIds, ok := rData["shortIds"].([]any)
  241. if ok && len(shortIds) > 0 {
  242. rltyData["shortId"] = shortIds[random.Num(len(shortIds))].(string)
  243. } else {
  244. rltyData["shortId"] = ""
  245. }
  246. serverNames, ok := rData["serverNames"].([]any)
  247. if ok && len(serverNames) > 0 {
  248. rltyData["serverName"] = serverNames[random.Num(len(serverNames))].(string)
  249. } else {
  250. rltyData["serverName"] = ""
  251. }
  252. return rltyData
  253. }
  254. func (s *SubJsonService) genVnext(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client, encryption string) json_util.RawMessage {
  255. outbound := Outbound{}
  256. usersData := make([]UserVnext, 1)
  257. usersData[0].ID = client.ID
  258. usersData[0].Level = 8
  259. if inbound.Protocol == model.VMESS {
  260. usersData[0].Security = client.Security
  261. }
  262. if inbound.Protocol == model.VLESS {
  263. usersData[0].Flow = client.Flow
  264. usersData[0].Encryption = encryption
  265. }
  266. vnextData := make([]VnextSetting, 1)
  267. vnextData[0] = VnextSetting{
  268. Address: inbound.Listen,
  269. Port: inbound.Port,
  270. Users: usersData,
  271. }
  272. outbound.Protocol = string(inbound.Protocol)
  273. outbound.Tag = "proxy"
  274. if s.mux != "" {
  275. outbound.Mux = json_util.RawMessage(s.mux)
  276. }
  277. outbound.StreamSettings = streamSettings
  278. outbound.Settings = OutboundSettings{
  279. Vnext: vnextData,
  280. }
  281. result, _ := json.MarshalIndent(outbound, "", " ")
  282. return result
  283. }
  284. func (s *SubJsonService) genServer(inbound *model.Inbound, streamSettings json_util.RawMessage, client model.Client) json_util.RawMessage {
  285. outbound := Outbound{}
  286. serverData := make([]ServerSetting, 1)
  287. serverData[0] = ServerSetting{
  288. Address: inbound.Listen,
  289. Port: inbound.Port,
  290. Level: 8,
  291. Password: client.Password,
  292. }
  293. if inbound.Protocol == model.Shadowsocks {
  294. var inboundSettings map[string]any
  295. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  296. method, _ := inboundSettings["method"].(string)
  297. serverData[0].Method = method
  298. // server password in multi-user 2022 protocols
  299. if strings.HasPrefix(method, "2022") {
  300. if serverPassword, ok := inboundSettings["password"].(string); ok {
  301. serverData[0].Password = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  302. }
  303. }
  304. }
  305. outbound.Protocol = string(inbound.Protocol)
  306. outbound.Tag = "proxy"
  307. if s.mux != "" {
  308. outbound.Mux = json_util.RawMessage(s.mux)
  309. }
  310. outbound.StreamSettings = streamSettings
  311. outbound.Settings = OutboundSettings{
  312. Servers: serverData,
  313. }
  314. result, _ := json.MarshalIndent(outbound, "", " ")
  315. return result
  316. }
  317. type Outbound struct {
  318. Protocol string `json:"protocol"`
  319. Tag string `json:"tag"`
  320. StreamSettings json_util.RawMessage `json:"streamSettings"`
  321. Mux json_util.RawMessage `json:"mux,omitempty"`
  322. ProxySettings map[string]any `json:"proxySettings,omitempty"`
  323. Settings OutboundSettings `json:"settings,omitempty"`
  324. }
  325. type OutboundSettings struct {
  326. Vnext []VnextSetting `json:"vnext,omitempty"`
  327. Servers []ServerSetting `json:"servers,omitempty"`
  328. }
  329. type VnextSetting struct {
  330. Address string `json:"address"`
  331. Port int `json:"port"`
  332. Users []UserVnext `json:"users"`
  333. }
  334. type UserVnext struct {
  335. Encryption string `json:"encryption,omitempty"`
  336. Flow string `json:"flow,omitempty"`
  337. ID string `json:"id"`
  338. Security string `json:"security,omitempty"`
  339. Level int `json:"level"`
  340. }
  341. type ServerSetting struct {
  342. Password string `json:"password"`
  343. Level int `json:"level"`
  344. Address string `json:"address"`
  345. Port int `json:"port"`
  346. Flow string `json:"flow,omitempty"`
  347. Method string `json:"method,omitempty"`
  348. }