subClashService.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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. // Hysteria has its own transport + TLS model, applyTransport /
  143. // applySecurity don't fit. IsHysteria also covers the literal
  144. // "hysteria2" protocol string (#4081).
  145. if model.IsHysteria(inbound.Protocol) {
  146. return s.buildHysteriaProxy(inbound, client, extraRemark)
  147. }
  148. proxy := map[string]any{
  149. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  150. "server": inbound.Listen,
  151. "port": inbound.Port,
  152. "udp": true,
  153. }
  154. network, _ := stream["network"].(string)
  155. if !s.applyTransport(proxy, network, stream) {
  156. return nil
  157. }
  158. switch inbound.Protocol {
  159. case model.VMESS:
  160. proxy["type"] = "vmess"
  161. proxy["uuid"] = client.ID
  162. proxy["alterId"] = 0
  163. cipher := client.Security
  164. if cipher == "" {
  165. cipher = "auto"
  166. }
  167. proxy["cipher"] = cipher
  168. case model.VLESS:
  169. proxy["type"] = "vless"
  170. proxy["uuid"] = client.ID
  171. if client.Flow != "" && network == "tcp" {
  172. proxy["flow"] = client.Flow
  173. }
  174. var inboundSettings map[string]any
  175. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  176. if encryption, ok := inboundSettings["encryption"].(string); ok && encryption != "" {
  177. proxy["packet-encoding"] = encryption
  178. }
  179. case model.Trojan:
  180. proxy["type"] = "trojan"
  181. proxy["password"] = client.Password
  182. case model.Shadowsocks:
  183. proxy["type"] = "ss"
  184. proxy["password"] = client.Password
  185. var inboundSettings map[string]any
  186. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  187. method, _ := inboundSettings["method"].(string)
  188. if method == "" {
  189. return nil
  190. }
  191. proxy["cipher"] = method
  192. if strings.HasPrefix(method, "2022") {
  193. if serverPassword, ok := inboundSettings["password"].(string); ok && serverPassword != "" {
  194. proxy["password"] = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  195. }
  196. }
  197. default:
  198. return nil
  199. }
  200. security, _ := stream["security"].(string)
  201. if !s.applySecurity(proxy, security, stream) {
  202. return nil
  203. }
  204. return proxy
  205. }
  206. // buildHysteriaProxy produces a mihomo-compatible Clash entry for a
  207. // Hysteria (v1) or Hysteria2 inbound. It reads `inbound.StreamSettings`
  208. // directly instead of going through streamData/tlsData, because those
  209. // helpers prune fields (like `allowInsecure` / the salamander obfs
  210. // block) that the hysteria proxy wants preserved.
  211. func (s *SubClashService) buildHysteriaProxy(inbound *model.Inbound, client model.Client, extraRemark string) map[string]any {
  212. var inboundSettings map[string]any
  213. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  214. proxyType := "hysteria2"
  215. authKey := "password"
  216. if v, ok := inboundSettings["version"].(float64); ok && int(v) == 1 {
  217. proxyType = "hysteria"
  218. authKey = "auth-str"
  219. }
  220. proxy := map[string]any{
  221. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  222. "type": proxyType,
  223. "server": inbound.Listen,
  224. "port": inbound.Port,
  225. "udp": true,
  226. authKey: client.Auth,
  227. }
  228. var rawStream map[string]any
  229. _ = json.Unmarshal([]byte(inbound.StreamSettings), &rawStream)
  230. // TLS details — hysteria always uses TLS.
  231. if tlsSettings, ok := rawStream["tlsSettings"].(map[string]any); ok {
  232. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  233. proxy["sni"] = serverName
  234. }
  235. if alpnList, ok := tlsSettings["alpn"].([]any); ok && len(alpnList) > 0 {
  236. out := make([]string, 0, len(alpnList))
  237. for _, a := range alpnList {
  238. if s, ok := a.(string); ok && s != "" {
  239. out = append(out, s)
  240. }
  241. }
  242. if len(out) > 0 {
  243. proxy["alpn"] = out
  244. }
  245. }
  246. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  247. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  248. proxy["skip-cert-verify"] = true
  249. }
  250. if fp, ok := inner["fingerprint"].(string); ok && fp != "" {
  251. proxy["client-fingerprint"] = fp
  252. }
  253. }
  254. }
  255. // Salamander obfs (Hysteria2). Read the same finalmask.udp[salamander]
  256. // block the subscription link generator uses.
  257. if finalmask, ok := rawStream["finalmask"].(map[string]any); ok {
  258. if udpMasks, ok := finalmask["udp"].([]any); ok {
  259. for _, m := range udpMasks {
  260. mask, _ := m.(map[string]any)
  261. if mask == nil || mask["type"] != "salamander" {
  262. continue
  263. }
  264. settings, _ := mask["settings"].(map[string]any)
  265. if pw, ok := settings["password"].(string); ok && pw != "" {
  266. proxy["obfs"] = "salamander"
  267. proxy["obfs-password"] = pw
  268. break
  269. }
  270. }
  271. }
  272. }
  273. return proxy
  274. }
  275. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  276. switch network {
  277. case "", "tcp":
  278. proxy["network"] = "tcp"
  279. tcp, _ := stream["tcpSettings"].(map[string]any)
  280. if tcp != nil {
  281. header, _ := tcp["header"].(map[string]any)
  282. if header != nil {
  283. typeStr, _ := header["type"].(string)
  284. if typeStr != "" && typeStr != "none" {
  285. return false
  286. }
  287. }
  288. }
  289. return true
  290. case "ws":
  291. proxy["network"] = "ws"
  292. ws, _ := stream["wsSettings"].(map[string]any)
  293. wsOpts := map[string]any{}
  294. if ws != nil {
  295. if path, ok := ws["path"].(string); ok && path != "" {
  296. wsOpts["path"] = path
  297. }
  298. host := ""
  299. if v, ok := ws["host"].(string); ok && v != "" {
  300. host = v
  301. } else if headers, ok := ws["headers"].(map[string]any); ok {
  302. host = searchHost(headers)
  303. }
  304. if host != "" {
  305. wsOpts["headers"] = map[string]any{"Host": host}
  306. }
  307. }
  308. if len(wsOpts) > 0 {
  309. proxy["ws-opts"] = wsOpts
  310. }
  311. return true
  312. case "grpc":
  313. proxy["network"] = "grpc"
  314. grpc, _ := stream["grpcSettings"].(map[string]any)
  315. grpcOpts := map[string]any{}
  316. if grpc != nil {
  317. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  318. grpcOpts["grpc-service-name"] = serviceName
  319. }
  320. }
  321. if len(grpcOpts) > 0 {
  322. proxy["grpc-opts"] = grpcOpts
  323. }
  324. return true
  325. default:
  326. return false
  327. }
  328. }
  329. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  330. switch security {
  331. case "", "none":
  332. proxy["tls"] = false
  333. return true
  334. case "tls":
  335. proxy["tls"] = true
  336. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  337. if tlsSettings != nil {
  338. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  339. proxy["servername"] = serverName
  340. switch proxy["type"] {
  341. case "trojan":
  342. proxy["sni"] = serverName
  343. }
  344. }
  345. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  346. proxy["client-fingerprint"] = fingerprint
  347. }
  348. }
  349. return true
  350. case "reality":
  351. proxy["tls"] = true
  352. realitySettings, _ := stream["realitySettings"].(map[string]any)
  353. if realitySettings == nil {
  354. return false
  355. }
  356. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  357. proxy["servername"] = serverName
  358. }
  359. realityOpts := map[string]any{}
  360. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  361. realityOpts["public-key"] = publicKey
  362. }
  363. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  364. realityOpts["short-id"] = shortID
  365. }
  366. if len(realityOpts) > 0 {
  367. proxy["reality-opts"] = realityOpts
  368. }
  369. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  370. proxy["client-fingerprint"] = fingerprint
  371. }
  372. return true
  373. default:
  374. return false
  375. }
  376. }
  377. func (s *SubClashService) streamData(stream string) map[string]any {
  378. var streamSettings map[string]any
  379. json.Unmarshal([]byte(stream), &streamSettings)
  380. security, _ := streamSettings["security"].(string)
  381. switch security {
  382. case "tls":
  383. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  384. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  385. }
  386. case "reality":
  387. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  388. streamSettings["realitySettings"] = s.realityData(realitySettings)
  389. }
  390. }
  391. delete(streamSettings, "sockopt")
  392. return streamSettings
  393. }
  394. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  395. tlsData := make(map[string]any, 1)
  396. tlsClientSettings, _ := tData["settings"].(map[string]any)
  397. tlsData["serverName"] = tData["serverName"]
  398. tlsData["alpn"] = tData["alpn"]
  399. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  400. tlsData["fingerprint"] = fingerprint
  401. }
  402. return tlsData
  403. }
  404. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  405. rDataOut := make(map[string]any, 1)
  406. realityClientSettings, _ := rData["settings"].(map[string]any)
  407. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  408. rDataOut["publicKey"] = publicKey
  409. }
  410. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  411. rDataOut["fingerprint"] = fingerprint
  412. }
  413. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  414. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  415. }
  416. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  417. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  418. }
  419. return rDataOut
  420. }
  421. func cloneMap(src map[string]any) map[string]any {
  422. if src == nil {
  423. return nil
  424. }
  425. dst := make(map[string]any, len(src))
  426. for k, v := range src {
  427. dst[k] = v
  428. }
  429. return dst
  430. }