subClashService.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. package sub
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/goccy/go-json"
  6. yaml "github.com/goccy/go-yaml"
  7. "github.com/mhsanaei/3x-ui/v2/database/model"
  8. "github.com/mhsanaei/3x-ui/v2/logger"
  9. "github.com/mhsanaei/3x-ui/v2/web/service"
  10. "github.com/mhsanaei/3x-ui/v2/xray"
  11. )
  12. type SubClashService struct {
  13. inboundService service.InboundService
  14. SubService *SubService
  15. }
  16. type ClashConfig struct {
  17. Proxies []map[string]any `yaml:"proxies"`
  18. ProxyGroups []map[string]any `yaml:"proxy-groups"`
  19. Rules []string `yaml:"rules"`
  20. }
  21. func NewSubClashService(subService *SubService) *SubClashService {
  22. return &SubClashService{SubService: subService}
  23. }
  24. func (s *SubClashService) GetClash(subId string, host string) (string, string, error) {
  25. inbounds, err := s.SubService.getInboundsBySubId(subId)
  26. if err != nil || len(inbounds) == 0 {
  27. return "", "", err
  28. }
  29. var traffic xray.ClientTraffic
  30. var clientTraffics []xray.ClientTraffic
  31. var proxies []map[string]any
  32. for _, inbound := range inbounds {
  33. clients, err := s.inboundService.GetClients(inbound)
  34. if err != nil {
  35. logger.Error("SubClashService - GetClients: Unable to get clients from inbound")
  36. }
  37. if clients == nil {
  38. continue
  39. }
  40. if len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  41. listen, port, streamSettings, err := s.SubService.getFallbackMaster(inbound.Listen, inbound.StreamSettings)
  42. if err == nil {
  43. inbound.Listen = listen
  44. inbound.Port = port
  45. inbound.StreamSettings = streamSettings
  46. }
  47. }
  48. for _, client := range clients {
  49. if client.Enable && client.SubID == subId {
  50. clientTraffics = append(clientTraffics, s.SubService.getClientTraffics(inbound.ClientStats, client.Email))
  51. proxies = append(proxies, s.getProxies(inbound, client, host)...)
  52. }
  53. }
  54. }
  55. if len(proxies) == 0 {
  56. return "", "", nil
  57. }
  58. for index, clientTraffic := range clientTraffics {
  59. if index == 0 {
  60. traffic.Up = clientTraffic.Up
  61. traffic.Down = clientTraffic.Down
  62. traffic.Total = clientTraffic.Total
  63. if clientTraffic.ExpiryTime > 0 {
  64. traffic.ExpiryTime = clientTraffic.ExpiryTime
  65. }
  66. } else {
  67. traffic.Up += clientTraffic.Up
  68. traffic.Down += clientTraffic.Down
  69. if traffic.Total == 0 || clientTraffic.Total == 0 {
  70. traffic.Total = 0
  71. } else {
  72. traffic.Total += clientTraffic.Total
  73. }
  74. if clientTraffic.ExpiryTime != traffic.ExpiryTime {
  75. traffic.ExpiryTime = 0
  76. }
  77. }
  78. }
  79. proxyNames := make([]string, 0, len(proxies)+1)
  80. for _, proxy := range proxies {
  81. if name, ok := proxy["name"].(string); ok && name != "" {
  82. proxyNames = append(proxyNames, name)
  83. }
  84. }
  85. proxyNames = append(proxyNames, "DIRECT")
  86. config := ClashConfig{
  87. Proxies: proxies,
  88. ProxyGroups: []map[string]any{{
  89. "name": "PROXY",
  90. "type": "select",
  91. "proxies": proxyNames,
  92. }},
  93. Rules: []string{"MATCH,PROXY"},
  94. }
  95. finalYAML, err := yaml.Marshal(config)
  96. if err != nil {
  97. return "", "", err
  98. }
  99. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  100. return string(finalYAML), header, nil
  101. }
  102. func (s *SubClashService) getProxies(inbound *model.Inbound, client model.Client, host string) []map[string]any {
  103. stream := s.streamData(inbound.StreamSettings)
  104. externalProxies, ok := stream["externalProxy"].([]any)
  105. if !ok || len(externalProxies) == 0 {
  106. externalProxies = []any{map[string]any{
  107. "forceTls": "same",
  108. "dest": host,
  109. "port": float64(inbound.Port),
  110. "remark": "",
  111. }}
  112. }
  113. delete(stream, "externalProxy")
  114. proxies := make([]map[string]any, 0, len(externalProxies))
  115. for _, ep := range externalProxies {
  116. extPrxy := ep.(map[string]any)
  117. workingInbound := *inbound
  118. workingInbound.Listen = extPrxy["dest"].(string)
  119. workingInbound.Port = int(extPrxy["port"].(float64))
  120. workingStream := cloneMap(stream)
  121. switch extPrxy["forceTls"].(string) {
  122. case "tls":
  123. if workingStream["security"] != "tls" {
  124. workingStream["security"] = "tls"
  125. workingStream["tlsSettings"] = map[string]any{}
  126. }
  127. case "none":
  128. if workingStream["security"] != "none" {
  129. workingStream["security"] = "none"
  130. delete(workingStream, "tlsSettings")
  131. delete(workingStream, "realitySettings")
  132. }
  133. }
  134. proxy := s.buildProxy(&workingInbound, client, workingStream, extPrxy["remark"].(string))
  135. if len(proxy) > 0 {
  136. proxies = append(proxies, proxy)
  137. }
  138. }
  139. return proxies
  140. }
  141. func (s *SubClashService) buildProxy(inbound *model.Inbound, client model.Client, stream map[string]any, extraRemark string) map[string]any {
  142. proxy := map[string]any{
  143. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  144. "server": inbound.Listen,
  145. "port": inbound.Port,
  146. "udp": true,
  147. }
  148. network, _ := stream["network"].(string)
  149. if !s.applyTransport(proxy, network, stream) {
  150. return nil
  151. }
  152. switch inbound.Protocol {
  153. case model.VMESS:
  154. proxy["type"] = "vmess"
  155. proxy["uuid"] = client.ID
  156. proxy["alterId"] = 0
  157. cipher := client.Security
  158. if cipher == "" {
  159. cipher = "auto"
  160. }
  161. proxy["cipher"] = cipher
  162. case model.VLESS:
  163. proxy["type"] = "vless"
  164. proxy["uuid"] = client.ID
  165. if client.Flow != "" && network == "tcp" {
  166. proxy["flow"] = client.Flow
  167. }
  168. var inboundSettings map[string]any
  169. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  170. if encryption, ok := inboundSettings["encryption"].(string); ok && encryption != "" {
  171. proxy["packet-encoding"] = encryption
  172. }
  173. case model.Trojan:
  174. proxy["type"] = "trojan"
  175. proxy["password"] = client.Password
  176. case model.Shadowsocks:
  177. proxy["type"] = "ss"
  178. proxy["password"] = client.Password
  179. var inboundSettings map[string]any
  180. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  181. method, _ := inboundSettings["method"].(string)
  182. if method == "" {
  183. return nil
  184. }
  185. proxy["cipher"] = method
  186. if strings.HasPrefix(method, "2022") {
  187. if serverPassword, ok := inboundSettings["password"].(string); ok && serverPassword != "" {
  188. proxy["password"] = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  189. }
  190. }
  191. default:
  192. return nil
  193. }
  194. security, _ := stream["security"].(string)
  195. if !s.applySecurity(proxy, security, stream) {
  196. return nil
  197. }
  198. return proxy
  199. }
  200. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  201. switch network {
  202. case "", "tcp":
  203. proxy["network"] = "tcp"
  204. tcp, _ := stream["tcpSettings"].(map[string]any)
  205. if tcp != nil {
  206. header, _ := tcp["header"].(map[string]any)
  207. if header != nil {
  208. typeStr, _ := header["type"].(string)
  209. if typeStr != "" && typeStr != "none" {
  210. return false
  211. }
  212. }
  213. }
  214. return true
  215. case "ws":
  216. proxy["network"] = "ws"
  217. ws, _ := stream["wsSettings"].(map[string]any)
  218. wsOpts := map[string]any{}
  219. if ws != nil {
  220. if path, ok := ws["path"].(string); ok && path != "" {
  221. wsOpts["path"] = path
  222. }
  223. host := ""
  224. if v, ok := ws["host"].(string); ok && v != "" {
  225. host = v
  226. } else if headers, ok := ws["headers"].(map[string]any); ok {
  227. host = searchHost(headers)
  228. }
  229. if host != "" {
  230. wsOpts["headers"] = map[string]any{"Host": host}
  231. }
  232. }
  233. if len(wsOpts) > 0 {
  234. proxy["ws-opts"] = wsOpts
  235. }
  236. return true
  237. case "grpc":
  238. proxy["network"] = "grpc"
  239. grpc, _ := stream["grpcSettings"].(map[string]any)
  240. grpcOpts := map[string]any{}
  241. if grpc != nil {
  242. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  243. grpcOpts["grpc-service-name"] = serviceName
  244. }
  245. }
  246. if len(grpcOpts) > 0 {
  247. proxy["grpc-opts"] = grpcOpts
  248. }
  249. return true
  250. default:
  251. return false
  252. }
  253. }
  254. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  255. switch security {
  256. case "", "none":
  257. proxy["tls"] = false
  258. return true
  259. case "tls":
  260. proxy["tls"] = true
  261. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  262. if tlsSettings != nil {
  263. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  264. proxy["servername"] = serverName
  265. switch proxy["type"] {
  266. case "trojan":
  267. proxy["sni"] = serverName
  268. }
  269. }
  270. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  271. proxy["client-fingerprint"] = fingerprint
  272. }
  273. }
  274. return true
  275. case "reality":
  276. proxy["tls"] = true
  277. realitySettings, _ := stream["realitySettings"].(map[string]any)
  278. if realitySettings == nil {
  279. return false
  280. }
  281. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  282. proxy["servername"] = serverName
  283. }
  284. realityOpts := map[string]any{}
  285. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  286. realityOpts["public-key"] = publicKey
  287. }
  288. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  289. realityOpts["short-id"] = shortID
  290. }
  291. if len(realityOpts) > 0 {
  292. proxy["reality-opts"] = realityOpts
  293. }
  294. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  295. proxy["client-fingerprint"] = fingerprint
  296. }
  297. return true
  298. default:
  299. return false
  300. }
  301. }
  302. func (s *SubClashService) streamData(stream string) map[string]any {
  303. var streamSettings map[string]any
  304. json.Unmarshal([]byte(stream), &streamSettings)
  305. security, _ := streamSettings["security"].(string)
  306. switch security {
  307. case "tls":
  308. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  309. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  310. }
  311. case "reality":
  312. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  313. streamSettings["realitySettings"] = s.realityData(realitySettings)
  314. }
  315. }
  316. delete(streamSettings, "sockopt")
  317. return streamSettings
  318. }
  319. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  320. tlsData := make(map[string]any, 1)
  321. tlsClientSettings, _ := tData["settings"].(map[string]any)
  322. tlsData["serverName"] = tData["serverName"]
  323. tlsData["alpn"] = tData["alpn"]
  324. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  325. tlsData["fingerprint"] = fingerprint
  326. }
  327. return tlsData
  328. }
  329. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  330. rDataOut := make(map[string]any, 1)
  331. realityClientSettings, _ := rData["settings"].(map[string]any)
  332. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  333. rDataOut["publicKey"] = publicKey
  334. }
  335. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  336. rDataOut["fingerprint"] = fingerprint
  337. }
  338. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  339. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  340. }
  341. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  342. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  343. }
  344. return rDataOut
  345. }
  346. func cloneMap(src map[string]any) map[string]any {
  347. if src == nil {
  348. return nil
  349. }
  350. dst := make(map[string]any, len(src))
  351. for k, v := range src {
  352. dst[k] = v
  353. }
  354. return dst
  355. }