1
0

subClashService.go 16 KB

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