subClashService.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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/v3/database/model"
  8. "github.com/mhsanaei/3x-ui/v3/logger"
  9. "github.com/mhsanaei/3x-ui/v3/web/service"
  10. "github.com/mhsanaei/3x-ui/v3/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. // Set per-request state so resolveInboundAddress sees the node map.
  26. s.SubService.PrepareForRequest(host)
  27. inbounds, err := s.SubService.getInboundsBySubId(subId)
  28. if err != nil || len(inbounds) == 0 {
  29. return "", "", err
  30. }
  31. var traffic xray.ClientTraffic
  32. var clientTraffics []xray.ClientTraffic
  33. var proxies []map[string]any
  34. seenEmails := make(map[string]struct{})
  35. for _, inbound := range inbounds {
  36. clients, err := s.inboundService.GetClients(inbound)
  37. if err != nil {
  38. logger.Error("SubClashService - GetClients: Unable to get clients from inbound")
  39. }
  40. if clients == nil {
  41. continue
  42. }
  43. if len(inbound.Listen) > 0 && inbound.Listen[0] == '@' {
  44. listen, port, streamSettings, err := s.SubService.getFallbackMaster(inbound.Listen, inbound.StreamSettings)
  45. if err == nil {
  46. inbound.Listen = listen
  47. inbound.Port = port
  48. inbound.StreamSettings = streamSettings
  49. }
  50. }
  51. for _, client := range clients {
  52. if client.SubID == subId {
  53. _, clientTraffics = s.SubService.appendUniqueTraffic(seenEmails, clientTraffics, inbound.ClientStats, client.Email)
  54. proxies = append(proxies, s.getProxies(inbound, client, host)...)
  55. }
  56. }
  57. }
  58. if len(proxies) == 0 {
  59. return "", "", nil
  60. }
  61. for index, clientTraffic := range clientTraffics {
  62. if index == 0 {
  63. traffic.Up = clientTraffic.Up
  64. traffic.Down = clientTraffic.Down
  65. traffic.Total = clientTraffic.Total
  66. if clientTraffic.ExpiryTime > 0 {
  67. traffic.ExpiryTime = clientTraffic.ExpiryTime
  68. }
  69. } else {
  70. traffic.Up += clientTraffic.Up
  71. traffic.Down += clientTraffic.Down
  72. if traffic.Total == 0 || clientTraffic.Total == 0 {
  73. traffic.Total = 0
  74. } else {
  75. traffic.Total += clientTraffic.Total
  76. }
  77. if clientTraffic.ExpiryTime != traffic.ExpiryTime {
  78. traffic.ExpiryTime = 0
  79. }
  80. }
  81. }
  82. proxyNames := make([]string, 0, len(proxies)+1)
  83. for _, proxy := range proxies {
  84. if name, ok := proxy["name"].(string); ok && name != "" {
  85. proxyNames = append(proxyNames, name)
  86. }
  87. }
  88. proxyNames = append(proxyNames, "DIRECT")
  89. config := ClashConfig{
  90. Proxies: proxies,
  91. ProxyGroups: []map[string]any{{
  92. "name": "PROXY",
  93. "type": "select",
  94. "proxies": proxyNames,
  95. }},
  96. Rules: []string{"MATCH,PROXY"},
  97. }
  98. finalYAML, err := yaml.Marshal(config)
  99. if err != nil {
  100. return "", "", err
  101. }
  102. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  103. return string(finalYAML), header, nil
  104. }
  105. func (s *SubClashService) getProxies(inbound *model.Inbound, client model.Client, host string) []map[string]any {
  106. stream := s.streamData(inbound.StreamSettings)
  107. // For node-managed inbounds the Clash proxy "server" must be the
  108. // node's address, not the request host. resolveInboundAddress handles
  109. // the node→listen→request-host fallback chain.
  110. defaultDest := s.SubService.resolveInboundAddress(inbound)
  111. if defaultDest == "" {
  112. defaultDest = host
  113. }
  114. externalProxies, ok := stream["externalProxy"].([]any)
  115. if !ok || len(externalProxies) == 0 {
  116. externalProxies = []any{map[string]any{
  117. "forceTls": "same",
  118. "dest": defaultDest,
  119. "port": float64(inbound.Port),
  120. "remark": "",
  121. }}
  122. }
  123. delete(stream, "externalProxy")
  124. proxies := make([]map[string]any, 0, len(externalProxies))
  125. for _, ep := range externalProxies {
  126. extPrxy := ep.(map[string]any)
  127. workingInbound := *inbound
  128. workingInbound.Listen = extPrxy["dest"].(string)
  129. workingInbound.Port = int(extPrxy["port"].(float64))
  130. workingStream := cloneMap(stream)
  131. switch extPrxy["forceTls"].(string) {
  132. case "tls":
  133. if workingStream["security"] != "tls" {
  134. workingStream["security"] = "tls"
  135. workingStream["tlsSettings"] = map[string]any{}
  136. }
  137. case "none":
  138. if workingStream["security"] != "none" {
  139. workingStream["security"] = "none"
  140. delete(workingStream, "tlsSettings")
  141. delete(workingStream, "realitySettings")
  142. }
  143. }
  144. proxy := s.buildProxy(&workingInbound, client, workingStream, extPrxy["remark"].(string))
  145. if len(proxy) > 0 {
  146. proxies = append(proxies, proxy)
  147. }
  148. }
  149. return proxies
  150. }
  151. func (s *SubClashService) buildProxy(inbound *model.Inbound, client model.Client, stream map[string]any, extraRemark string) map[string]any {
  152. // Hysteria has its own transport + TLS model, applyTransport /
  153. // applySecurity don't fit. IsHysteria also covers the literal
  154. // "hysteria2" protocol string (#4081).
  155. if model.IsHysteria(inbound.Protocol) {
  156. return s.buildHysteriaProxy(inbound, client, extraRemark)
  157. }
  158. proxy := map[string]any{
  159. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  160. "server": inbound.Listen,
  161. "port": inbound.Port,
  162. "udp": true,
  163. }
  164. network, _ := stream["network"].(string)
  165. if !s.applyTransport(proxy, network, stream) {
  166. return nil
  167. }
  168. switch inbound.Protocol {
  169. case model.VMESS:
  170. proxy["type"] = "vmess"
  171. proxy["uuid"] = client.ID
  172. proxy["alterId"] = 0
  173. cipher := client.Security
  174. if cipher == "" {
  175. cipher = "auto"
  176. }
  177. proxy["cipher"] = cipher
  178. case model.VLESS:
  179. proxy["type"] = "vless"
  180. proxy["uuid"] = client.ID
  181. if client.Flow != "" && network == "tcp" {
  182. proxy["flow"] = client.Flow
  183. }
  184. var inboundSettings map[string]any
  185. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  186. if encryption, ok := inboundSettings["encryption"].(string); ok && encryption != "" {
  187. proxy["packet-encoding"] = encryption
  188. }
  189. case model.Trojan:
  190. proxy["type"] = "trojan"
  191. proxy["password"] = client.Password
  192. case model.Shadowsocks:
  193. proxy["type"] = "ss"
  194. proxy["password"] = client.Password
  195. var inboundSettings map[string]any
  196. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  197. method, _ := inboundSettings["method"].(string)
  198. if method == "" {
  199. return nil
  200. }
  201. proxy["cipher"] = method
  202. if strings.HasPrefix(method, "2022") {
  203. if serverPassword, ok := inboundSettings["password"].(string); ok && serverPassword != "" {
  204. proxy["password"] = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  205. }
  206. }
  207. default:
  208. return nil
  209. }
  210. security, _ := stream["security"].(string)
  211. if !s.applySecurity(proxy, security, stream) {
  212. return nil
  213. }
  214. return proxy
  215. }
  216. // buildHysteriaProxy produces a mihomo-compatible Clash entry for a
  217. // Hysteria (v1) or Hysteria2 inbound. It reads `inbound.StreamSettings`
  218. // directly instead of going through streamData/tlsData, because those
  219. // helpers prune fields (like `allowInsecure` / the salamander obfs
  220. // block) that the hysteria proxy wants preserved.
  221. func (s *SubClashService) buildHysteriaProxy(inbound *model.Inbound, client model.Client, extraRemark string) map[string]any {
  222. var inboundSettings map[string]any
  223. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  224. proxyType := "hysteria2"
  225. authKey := "password"
  226. if v, ok := inboundSettings["version"].(float64); ok && int(v) == 1 {
  227. proxyType = "hysteria"
  228. authKey = "auth-str"
  229. }
  230. proxy := map[string]any{
  231. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  232. "type": proxyType,
  233. "server": inbound.Listen,
  234. "port": inbound.Port,
  235. "udp": true,
  236. authKey: client.Auth,
  237. }
  238. var rawStream map[string]any
  239. _ = json.Unmarshal([]byte(inbound.StreamSettings), &rawStream)
  240. // TLS details — hysteria always uses TLS.
  241. if tlsSettings, ok := rawStream["tlsSettings"].(map[string]any); ok {
  242. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  243. proxy["sni"] = serverName
  244. }
  245. if alpnList, ok := tlsSettings["alpn"].([]any); ok && len(alpnList) > 0 {
  246. out := make([]string, 0, len(alpnList))
  247. for _, a := range alpnList {
  248. if s, ok := a.(string); ok && s != "" {
  249. out = append(out, s)
  250. }
  251. }
  252. if len(out) > 0 {
  253. proxy["alpn"] = out
  254. }
  255. }
  256. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  257. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  258. proxy["skip-cert-verify"] = true
  259. }
  260. if fp, ok := inner["fingerprint"].(string); ok && fp != "" {
  261. proxy["client-fingerprint"] = fp
  262. }
  263. }
  264. }
  265. // Salamander obfs (Hysteria2). Read the same finalmask.udp[salamander]
  266. // block the subscription link generator uses.
  267. if finalmask, ok := rawStream["finalmask"].(map[string]any); ok {
  268. if udpMasks, ok := finalmask["udp"].([]any); ok {
  269. for _, m := range udpMasks {
  270. mask, _ := m.(map[string]any)
  271. if mask == nil || mask["type"] != "salamander" {
  272. continue
  273. }
  274. settings, _ := mask["settings"].(map[string]any)
  275. if pw, ok := settings["password"].(string); ok && pw != "" {
  276. proxy["obfs"] = "salamander"
  277. proxy["obfs-password"] = pw
  278. break
  279. }
  280. }
  281. }
  282. }
  283. return proxy
  284. }
  285. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  286. switch network {
  287. case "", "tcp":
  288. proxy["network"] = "tcp"
  289. tcp, _ := stream["tcpSettings"].(map[string]any)
  290. if tcp != nil {
  291. header, _ := tcp["header"].(map[string]any)
  292. if header != nil {
  293. typeStr, _ := header["type"].(string)
  294. if typeStr != "" && typeStr != "none" {
  295. return false
  296. }
  297. }
  298. }
  299. return true
  300. case "ws":
  301. proxy["network"] = "ws"
  302. ws, _ := stream["wsSettings"].(map[string]any)
  303. wsOpts := map[string]any{}
  304. if ws != nil {
  305. if path, ok := ws["path"].(string); ok && path != "" {
  306. wsOpts["path"] = path
  307. }
  308. host := ""
  309. if v, ok := ws["host"].(string); ok && v != "" {
  310. host = v
  311. } else if headers, ok := ws["headers"].(map[string]any); ok {
  312. host = searchHost(headers)
  313. }
  314. if host != "" {
  315. wsOpts["headers"] = map[string]any{"Host": host}
  316. }
  317. }
  318. if len(wsOpts) > 0 {
  319. proxy["ws-opts"] = wsOpts
  320. }
  321. return true
  322. case "grpc":
  323. proxy["network"] = "grpc"
  324. grpc, _ := stream["grpcSettings"].(map[string]any)
  325. grpcOpts := map[string]any{}
  326. if grpc != nil {
  327. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  328. grpcOpts["grpc-service-name"] = serviceName
  329. }
  330. }
  331. if len(grpcOpts) > 0 {
  332. proxy["grpc-opts"] = grpcOpts
  333. }
  334. return true
  335. default:
  336. return false
  337. }
  338. }
  339. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  340. switch security {
  341. case "", "none":
  342. proxy["tls"] = false
  343. return true
  344. case "tls":
  345. proxy["tls"] = true
  346. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  347. if tlsSettings != nil {
  348. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  349. proxy["servername"] = serverName
  350. switch proxy["type"] {
  351. case "trojan":
  352. proxy["sni"] = serverName
  353. }
  354. }
  355. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  356. proxy["client-fingerprint"] = fingerprint
  357. }
  358. }
  359. return true
  360. case "reality":
  361. proxy["tls"] = true
  362. realitySettings, _ := stream["realitySettings"].(map[string]any)
  363. if realitySettings == nil {
  364. return false
  365. }
  366. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  367. proxy["servername"] = serverName
  368. }
  369. realityOpts := map[string]any{}
  370. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  371. realityOpts["public-key"] = publicKey
  372. }
  373. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  374. realityOpts["short-id"] = shortID
  375. }
  376. if len(realityOpts) > 0 {
  377. proxy["reality-opts"] = realityOpts
  378. }
  379. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  380. proxy["client-fingerprint"] = fingerprint
  381. }
  382. return true
  383. default:
  384. return false
  385. }
  386. }
  387. func (s *SubClashService) streamData(stream string) map[string]any {
  388. var streamSettings map[string]any
  389. json.Unmarshal([]byte(stream), &streamSettings)
  390. security, _ := streamSettings["security"].(string)
  391. switch security {
  392. case "tls":
  393. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  394. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  395. }
  396. case "reality":
  397. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  398. streamSettings["realitySettings"] = s.realityData(realitySettings)
  399. }
  400. }
  401. delete(streamSettings, "sockopt")
  402. return streamSettings
  403. }
  404. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  405. tlsData := make(map[string]any, 1)
  406. tlsClientSettings, _ := tData["settings"].(map[string]any)
  407. tlsData["serverName"] = tData["serverName"]
  408. tlsData["alpn"] = tData["alpn"]
  409. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  410. tlsData["fingerprint"] = fingerprint
  411. }
  412. return tlsData
  413. }
  414. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  415. rDataOut := make(map[string]any, 1)
  416. realityClientSettings, _ := rData["settings"].(map[string]any)
  417. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  418. rDataOut["publicKey"] = publicKey
  419. }
  420. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  421. rDataOut["fingerprint"] = fingerprint
  422. }
  423. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  424. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  425. }
  426. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  427. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  428. }
  429. return rDataOut
  430. }
  431. func cloneMap(src map[string]any) map[string]any {
  432. if src == nil {
  433. return nil
  434. }
  435. dst := make(map[string]any, len(src))
  436. for k, v := range src {
  437. dst[k] = v
  438. }
  439. return dst
  440. }