subClashService.go 14 KB

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