clash_service.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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/internal/database/model"
  9. )
  10. type SubClashService struct {
  11. enableRouting bool
  12. clashRules string
  13. SubService *SubService
  14. }
  15. func NewSubClashService(enableRouting bool, clashRules string, subService *SubService) *SubClashService {
  16. return &SubClashService{enableRouting: enableRouting, clashRules: clashRules, SubService: subService}
  17. }
  18. func (s *SubClashService) GetClash(subId string, host string) (string, string, error) {
  19. // Set per-request state so resolveInboundAddress sees the node map.
  20. s.SubService.PrepareForRequest(host)
  21. inbounds, err := s.SubService.getInboundsBySubId(subId)
  22. if err != nil || len(inbounds) == 0 {
  23. return "", "", err
  24. }
  25. var proxies []map[string]any
  26. seenEmails := make(map[string]struct{})
  27. for _, inbound := range inbounds {
  28. clients := s.SubService.matchingClients(inbound, subId)
  29. if len(clients) == 0 {
  30. continue
  31. }
  32. s.SubService.projectThroughFallbackMaster(inbound)
  33. for _, client := range clients {
  34. seenEmails[client.Email] = struct{}{}
  35. proxies = append(proxies, s.getProxies(inbound, client, host)...)
  36. }
  37. }
  38. if len(proxies) == 0 {
  39. return "", "", nil
  40. }
  41. ensureUniqueProxyNames(proxies)
  42. emails := make([]string, 0, len(seenEmails))
  43. for e := range seenEmails {
  44. emails = append(emails, e)
  45. }
  46. traffic, _ := s.SubService.AggregateTrafficByEmails(emails)
  47. proxyNames := make([]string, 0, len(proxies)+1)
  48. for _, proxy := range proxies {
  49. if name, ok := proxy["name"].(string); ok && name != "" {
  50. proxyNames = append(proxyNames, name)
  51. }
  52. }
  53. proxyNames = append(proxyNames, "DIRECT")
  54. config := map[string]any{
  55. "proxies": proxies,
  56. "proxy-groups": []map[string]any{{
  57. "name": "PROXY",
  58. "type": "select",
  59. "proxies": proxyNames,
  60. }},
  61. "rules": []string{"MATCH,PROXY"},
  62. }
  63. if s.enableRouting {
  64. if err := mergeClashRulesYAML(config, s.clashRules); err != nil {
  65. return "", "", err
  66. }
  67. }
  68. finalYAML, err := yaml.Marshal(config)
  69. if err != nil {
  70. return "", "", err
  71. }
  72. header := fmt.Sprintf("upload=%d; download=%d; total=%d; expire=%d", traffic.Up, traffic.Down, traffic.Total, traffic.ExpiryTime/1000)
  73. return string(finalYAML), header, nil
  74. }
  75. // ensureUniqueProxyNames keeps every proxy "name" non-empty and unique:
  76. // mihomo rejects the whole config on a duplicate name (the empty string
  77. // genRemark returns for a remark-less inbound counts), vanishing the Clash
  78. // profile on refresh. See issue #4641.
  79. func ensureUniqueProxyNames(proxies []map[string]any) {
  80. seen := make(map[string]struct{}, len(proxies))
  81. for i, proxy := range proxies {
  82. base, _ := proxy["name"].(string)
  83. if base == "" {
  84. base = fallbackProxyName(proxy, i)
  85. }
  86. name := base
  87. for n := 2; ; n++ {
  88. if _, dup := seen[name]; !dup {
  89. break
  90. }
  91. name = fmt.Sprintf("%s-%d", base, n)
  92. }
  93. seen[name] = struct{}{}
  94. proxy["name"] = name
  95. }
  96. }
  97. func fallbackProxyName(proxy map[string]any, idx int) string {
  98. typ, _ := proxy["type"].(string)
  99. server, _ := proxy["server"].(string)
  100. if typ != "" && server != "" {
  101. return fmt.Sprintf("%s-%s-%v", typ, server, proxy["port"])
  102. }
  103. return fmt.Sprintf("proxy-%d", idx+1)
  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→subscriber-host fallback chain.
  110. defaultDest := s.SubService.resolveInboundAddress(inbound)
  111. if defaultDest == "" {
  112. defaultDest = host
  113. }
  114. externalProxies, ok := stream["externalProxy"].([]any)
  115. hasExternalProxy := ok && len(externalProxies) > 0
  116. if !hasExternalProxy {
  117. externalProxies = []any{map[string]any{
  118. "forceTls": "same",
  119. "dest": defaultDest,
  120. "port": float64(inbound.Port),
  121. "remark": "",
  122. }}
  123. }
  124. delete(stream, "externalProxy")
  125. proxies := make([]map[string]any, 0, len(externalProxies))
  126. for _, ep := range externalProxies {
  127. extPrxy := ep.(map[string]any)
  128. workingInbound := *inbound
  129. workingInbound.Listen = extPrxy["dest"].(string)
  130. workingInbound.Port = int(extPrxy["port"].(float64))
  131. workingStream := cloneStreamForExternalProxy(stream)
  132. switch extPrxy["forceTls"].(string) {
  133. case "tls":
  134. if workingStream["security"] != "tls" {
  135. workingStream["security"] = "tls"
  136. workingStream["tlsSettings"] = map[string]any{}
  137. }
  138. case "none":
  139. if workingStream["security"] != "none" {
  140. workingStream["security"] = "none"
  141. delete(workingStream, "tlsSettings")
  142. delete(workingStream, "realitySettings")
  143. }
  144. }
  145. security, _ := workingStream["security"].(string)
  146. if hasExternalProxy {
  147. applyExternalProxyTLSToStream(extPrxy, workingStream, security)
  148. }
  149. proxy := s.buildProxy(&workingInbound, client, workingStream, extPrxy["remark"].(string))
  150. if len(proxy) > 0 {
  151. proxies = append(proxies, proxy)
  152. }
  153. }
  154. return proxies
  155. }
  156. func (s *SubClashService) buildProxy(inbound *model.Inbound, client model.Client, stream map[string]any, extraRemark string) map[string]any {
  157. // Hysteria has its own transport + TLS model, applyTransport /
  158. // applySecurity don't fit.
  159. if inbound.Protocol == model.Hysteria {
  160. return s.buildHysteriaProxy(inbound, client, extraRemark)
  161. }
  162. proxy := map[string]any{
  163. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  164. "server": inbound.Listen,
  165. "port": inbound.Port,
  166. "udp": true,
  167. }
  168. network, _ := stream["network"].(string)
  169. if !s.applyTransport(proxy, network, stream) {
  170. return nil
  171. }
  172. switch inbound.Protocol {
  173. case model.VMESS:
  174. proxy["type"] = "vmess"
  175. proxy["uuid"] = client.ID
  176. proxy["alterId"] = 0
  177. cipher := client.Security
  178. if cipher == "" {
  179. cipher = "auto"
  180. }
  181. proxy["cipher"] = cipher
  182. case model.VLESS:
  183. proxy["type"] = "vless"
  184. proxy["uuid"] = client.ID
  185. if client.Flow != "" && network == "tcp" {
  186. proxy["flow"] = client.Flow
  187. }
  188. var inboundSettings map[string]any
  189. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  190. if encryption, ok := inboundSettings["encryption"].(string); ok {
  191. encryption = strings.TrimSpace(encryption)
  192. if encryption != "" && encryption != "none" {
  193. proxy["encryption"] = encryption
  194. }
  195. }
  196. case model.Trojan:
  197. proxy["type"] = "trojan"
  198. proxy["password"] = client.Password
  199. case model.Shadowsocks:
  200. proxy["type"] = "ss"
  201. proxy["password"] = client.Password
  202. var inboundSettings map[string]any
  203. json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  204. method, _ := inboundSettings["method"].(string)
  205. if method == "" {
  206. return nil
  207. }
  208. proxy["cipher"] = method
  209. if strings.HasPrefix(method, "2022") {
  210. if serverPassword, ok := inboundSettings["password"].(string); ok && serverPassword != "" {
  211. proxy["password"] = fmt.Sprintf("%s:%s", serverPassword, client.Password)
  212. }
  213. }
  214. default:
  215. return nil
  216. }
  217. security, _ := stream["security"].(string)
  218. if !s.applySecurity(proxy, security, stream) {
  219. return nil
  220. }
  221. return proxy
  222. }
  223. // buildHysteriaProxy produces a mihomo-compatible Clash entry for a
  224. // Hysteria (v1) or Hysteria2 inbound. It reads `inbound.StreamSettings`
  225. // directly instead of going through streamData/tlsData, because those
  226. // helpers prune fields (like `allowInsecure` / the salamander obfs
  227. // block) that the hysteria proxy wants preserved.
  228. func (s *SubClashService) buildHysteriaProxy(inbound *model.Inbound, client model.Client, extraRemark string) map[string]any {
  229. var inboundSettings map[string]any
  230. _ = json.Unmarshal([]byte(inbound.Settings), &inboundSettings)
  231. proxyType := "hysteria2"
  232. authKey := "password"
  233. if v, ok := inboundSettings["version"].(float64); ok && int(v) == 1 {
  234. proxyType = "hysteria"
  235. authKey = "auth-str"
  236. }
  237. proxy := map[string]any{
  238. "name": s.SubService.genRemark(inbound, client.Email, extraRemark),
  239. "type": proxyType,
  240. "server": inbound.Listen,
  241. "port": inbound.Port,
  242. "udp": true,
  243. authKey: client.Auth,
  244. }
  245. var rawStream map[string]any
  246. _ = json.Unmarshal([]byte(inbound.StreamSettings), &rawStream)
  247. // TLS details — hysteria always uses TLS.
  248. if tlsSettings, ok := rawStream["tlsSettings"].(map[string]any); ok {
  249. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  250. proxy["sni"] = serverName
  251. }
  252. if alpnList, ok := tlsSettings["alpn"].([]any); ok && len(alpnList) > 0 {
  253. out := make([]string, 0, len(alpnList))
  254. for _, a := range alpnList {
  255. if s, ok := a.(string); ok && s != "" {
  256. out = append(out, s)
  257. }
  258. }
  259. if len(out) > 0 {
  260. proxy["alpn"] = out
  261. }
  262. }
  263. if inner, ok := tlsSettings["settings"].(map[string]any); ok {
  264. if insecure, ok := inner["allowInsecure"].(bool); ok && insecure {
  265. proxy["skip-cert-verify"] = true
  266. }
  267. if fp, ok := inner["fingerprint"].(string); ok && fp != "" {
  268. proxy["client-fingerprint"] = fp
  269. }
  270. }
  271. }
  272. // Salamander obfs (Hysteria2). Read the same finalmask.udp[salamander]
  273. // block the subscription link generator uses.
  274. if finalmask, ok := rawStream["finalmask"].(map[string]any); ok {
  275. if udpMasks, ok := finalmask["udp"].([]any); ok {
  276. for _, m := range udpMasks {
  277. mask, _ := m.(map[string]any)
  278. if mask == nil || mask["type"] != "salamander" {
  279. continue
  280. }
  281. settings, _ := mask["settings"].(map[string]any)
  282. if pw, ok := settings["password"].(string); ok && pw != "" {
  283. proxy["obfs"] = "salamander"
  284. proxy["obfs-password"] = pw
  285. break
  286. }
  287. }
  288. }
  289. }
  290. // UDP port hopping. mihomo reads the range from a dedicated `ports`
  291. // field (the base `port` stays as the redirect target).
  292. if hopPorts := hysteriaHopPorts(rawStream); hopPorts != "" {
  293. proxy["ports"] = hopPorts
  294. }
  295. return proxy
  296. }
  297. func (s *SubClashService) applyTransport(proxy map[string]any, network string, stream map[string]any) bool {
  298. switch network {
  299. case "", "tcp":
  300. proxy["network"] = "tcp"
  301. tcp, _ := stream["tcpSettings"].(map[string]any)
  302. if tcp != nil {
  303. header, _ := tcp["header"].(map[string]any)
  304. if header != nil {
  305. typeStr, _ := header["type"].(string)
  306. if typeStr != "" && typeStr != "none" {
  307. return false
  308. }
  309. }
  310. }
  311. return true
  312. case "ws":
  313. proxy["network"] = "ws"
  314. ws, _ := stream["wsSettings"].(map[string]any)
  315. wsOpts := map[string]any{}
  316. if ws != nil {
  317. if path, ok := ws["path"].(string); ok && path != "" {
  318. wsOpts["path"] = path
  319. }
  320. host := ""
  321. if v, ok := ws["host"].(string); ok && v != "" {
  322. host = v
  323. } else if headers, ok := ws["headers"].(map[string]any); ok {
  324. host = searchHost(headers)
  325. }
  326. if host != "" {
  327. wsOpts["headers"] = map[string]any{"Host": host}
  328. }
  329. }
  330. if len(wsOpts) > 0 {
  331. proxy["ws-opts"] = wsOpts
  332. }
  333. return true
  334. case "grpc":
  335. proxy["network"] = "grpc"
  336. grpc, _ := stream["grpcSettings"].(map[string]any)
  337. grpcOpts := map[string]any{}
  338. if grpc != nil {
  339. if serviceName, ok := grpc["serviceName"].(string); ok && serviceName != "" {
  340. grpcOpts["grpc-service-name"] = serviceName
  341. }
  342. }
  343. if len(grpcOpts) > 0 {
  344. proxy["grpc-opts"] = grpcOpts
  345. }
  346. return true
  347. case "httpupgrade":
  348. proxy["network"] = "httpupgrade"
  349. hu, _ := stream["httpupgradeSettings"].(map[string]any)
  350. opts := map[string]any{}
  351. if hu != nil {
  352. if path, ok := hu["path"].(string); ok && path != "" {
  353. opts["path"] = path
  354. }
  355. host := ""
  356. if v, ok := hu["host"].(string); ok && v != "" {
  357. host = v
  358. } else if headers, ok := hu["headers"].(map[string]any); ok {
  359. host = searchHost(headers)
  360. }
  361. if host != "" {
  362. opts["headers"] = map[string]any{"Host": host}
  363. }
  364. }
  365. if len(opts) > 0 {
  366. proxy["http-upgrade-opts"] = opts
  367. }
  368. return true
  369. case "xhttp":
  370. proxy["network"] = "xhttp"
  371. xhttp, _ := stream["xhttpSettings"].(map[string]any)
  372. opts := map[string]any{}
  373. if xhttp != nil {
  374. if path, ok := xhttp["path"].(string); ok && path != "" {
  375. opts["path"] = path
  376. }
  377. host := ""
  378. if v, ok := xhttp["host"].(string); ok && v != "" {
  379. host = v
  380. } else if headers, ok := xhttp["headers"].(map[string]any); ok {
  381. host = searchHost(headers)
  382. }
  383. if host != "" {
  384. opts["host"] = host
  385. }
  386. if mode, ok := xhttp["mode"].(string); ok && mode != "" {
  387. opts["mode"] = mode
  388. }
  389. }
  390. if len(opts) > 0 {
  391. proxy["xhttp-opts"] = opts
  392. }
  393. return true
  394. default:
  395. return false
  396. }
  397. }
  398. func (s *SubClashService) applySecurity(proxy map[string]any, security string, stream map[string]any) bool {
  399. switch security {
  400. case "", "none":
  401. proxy["tls"] = false
  402. return true
  403. case "tls":
  404. proxy["tls"] = true
  405. tlsSettings, _ := stream["tlsSettings"].(map[string]any)
  406. if tlsSettings != nil {
  407. if serverName, ok := tlsSettings["serverName"].(string); ok && serverName != "" {
  408. proxy["servername"] = serverName
  409. switch proxy["type"] {
  410. case "trojan":
  411. proxy["sni"] = serverName
  412. }
  413. }
  414. if fingerprint, ok := tlsSettings["fingerprint"].(string); ok && fingerprint != "" {
  415. proxy["client-fingerprint"] = fingerprint
  416. }
  417. if alpn, ok := externalProxyALPNList(tlsSettings["alpn"]); ok {
  418. out := make([]string, 0, len(alpn))
  419. for _, item := range alpn {
  420. if s, ok := item.(string); ok && s != "" {
  421. out = append(out, s)
  422. }
  423. }
  424. if len(out) > 0 {
  425. proxy["alpn"] = out
  426. }
  427. }
  428. }
  429. return true
  430. case "reality":
  431. proxy["tls"] = true
  432. realitySettings, _ := stream["realitySettings"].(map[string]any)
  433. if realitySettings == nil {
  434. return false
  435. }
  436. if serverName, ok := realitySettings["serverName"].(string); ok && serverName != "" {
  437. proxy["servername"] = serverName
  438. }
  439. realityOpts := map[string]any{}
  440. if publicKey, ok := realitySettings["publicKey"].(string); ok && publicKey != "" {
  441. realityOpts["public-key"] = publicKey
  442. }
  443. if shortID, ok := realitySettings["shortId"].(string); ok && shortID != "" {
  444. realityOpts["short-id"] = shortID
  445. }
  446. if len(realityOpts) > 0 {
  447. proxy["reality-opts"] = realityOpts
  448. }
  449. if fingerprint, ok := realitySettings["fingerprint"].(string); ok && fingerprint != "" {
  450. proxy["client-fingerprint"] = fingerprint
  451. }
  452. return true
  453. default:
  454. return false
  455. }
  456. }
  457. func (s *SubClashService) streamData(stream string) map[string]any {
  458. var streamSettings map[string]any
  459. json.Unmarshal([]byte(stream), &streamSettings)
  460. security, _ := streamSettings["security"].(string)
  461. switch security {
  462. case "tls":
  463. if tlsSettings, ok := streamSettings["tlsSettings"].(map[string]any); ok {
  464. streamSettings["tlsSettings"] = s.tlsData(tlsSettings)
  465. }
  466. case "reality":
  467. if realitySettings, ok := streamSettings["realitySettings"].(map[string]any); ok {
  468. streamSettings["realitySettings"] = s.realityData(realitySettings)
  469. }
  470. }
  471. delete(streamSettings, "sockopt")
  472. return streamSettings
  473. }
  474. func (s *SubClashService) tlsData(tData map[string]any) map[string]any {
  475. tlsData := make(map[string]any, 1)
  476. tlsClientSettings, _ := tData["settings"].(map[string]any)
  477. tlsData["serverName"] = tData["serverName"]
  478. tlsData["alpn"] = tData["alpn"]
  479. if fingerprint, ok := tlsClientSettings["fingerprint"].(string); ok {
  480. tlsData["fingerprint"] = fingerprint
  481. }
  482. if pins, ok := tlsClientSettings["pinnedPeerCertSha256"].([]any); ok && len(pins) > 0 {
  483. tlsData["pin-sha256"] = pins
  484. }
  485. return tlsData
  486. }
  487. func (s *SubClashService) realityData(rData map[string]any) map[string]any {
  488. rDataOut := make(map[string]any, 1)
  489. realityClientSettings, _ := rData["settings"].(map[string]any)
  490. if publicKey, ok := realityClientSettings["publicKey"].(string); ok {
  491. rDataOut["publicKey"] = publicKey
  492. }
  493. if fingerprint, ok := realityClientSettings["fingerprint"].(string); ok {
  494. rDataOut["fingerprint"] = fingerprint
  495. }
  496. if serverNames, ok := rData["serverNames"].([]any); ok && len(serverNames) > 0 {
  497. rDataOut["serverName"] = fmt.Sprint(serverNames[0])
  498. }
  499. if shortIDs, ok := rData["shortIds"].([]any); ok && len(shortIDs) > 0 {
  500. rDataOut["shortId"] = fmt.Sprint(shortIDs[0])
  501. }
  502. return rDataOut
  503. }
  504. func cloneMap(src map[string]any) map[string]any {
  505. if src == nil {
  506. return nil
  507. }
  508. dst := make(map[string]any, len(src))
  509. maps.Copy(dst, src)
  510. return dst
  511. }
  512. func mergeClashRulesYAML(base map[string]any, raw string) error {
  513. raw = strings.TrimSpace(raw)
  514. if raw == "" {
  515. return nil
  516. }
  517. var custom any
  518. if err := yaml.Unmarshal([]byte(raw), &custom); err != nil {
  519. mergeClashRules(base, linesToClashRules(raw))
  520. return nil
  521. }
  522. switch typed := custom.(type) {
  523. case []any:
  524. mergeClashRules(base, typed)
  525. case map[string]any:
  526. for key, value := range typed {
  527. if key == "rules" {
  528. if ruleList, ok := asAnySlice(value); ok {
  529. mergeClashRules(base, ruleList)
  530. }
  531. continue
  532. }
  533. base[key] = value
  534. }
  535. default:
  536. mergeClashRules(base, linesToClashRules(raw))
  537. }
  538. return nil
  539. }
  540. func mergeClashRules(base map[string]any, customRules []any) {
  541. if len(customRules) == 0 {
  542. return
  543. }
  544. baseRules, _ := asAnySlice(base["rules"])
  545. if hasClashMatchRule(customRules) {
  546. base["rules"] = customRules
  547. return
  548. }
  549. merged := make([]any, 0, len(customRules)+len(baseRules))
  550. merged = append(merged, customRules...)
  551. merged = append(merged, baseRules...)
  552. base["rules"] = merged
  553. }
  554. func asAnySlice(value any) ([]any, bool) {
  555. switch typed := value.(type) {
  556. case []any:
  557. return typed, true
  558. case []string:
  559. out := make([]any, 0, len(typed))
  560. for _, item := range typed {
  561. out = append(out, item)
  562. }
  563. return out, true
  564. case []map[string]any:
  565. out := make([]any, 0, len(typed))
  566. for _, item := range typed {
  567. out = append(out, item)
  568. }
  569. return out, true
  570. default:
  571. return nil, false
  572. }
  573. }
  574. func hasClashMatchRule(rules []any) bool {
  575. for _, rule := range rules {
  576. ruleText, ok := rule.(string)
  577. if !ok {
  578. continue
  579. }
  580. parts := strings.SplitN(ruleText, ",", 2)
  581. if strings.EqualFold(strings.TrimSpace(parts[0]), "MATCH") {
  582. return true
  583. }
  584. }
  585. return false
  586. }
  587. func linesToClashRules(raw string) []any {
  588. lines := strings.Split(raw, "\n")
  589. rules := make([]any, 0, len(lines))
  590. for _, line := range lines {
  591. line = strings.TrimSpace(line)
  592. if line == "" || strings.HasPrefix(line, "#") {
  593. continue
  594. }
  595. rules = append(rules, line)
  596. }
  597. return rules
  598. }